java 基礎--NIO.2 – Path 、 Paths 、 Files


                                                                Path 、 Paths 、 Files    簡介 

1.    隨着 JDK 7 的發布, Java 對 NIO 進行了 極大的擴 展,增強了對文件處理和文件系統特性的支持, 以至於我們稱他們為 NIO.2 。

                 因為 NIO提供的 一些功能, NIO 已經成為文件處理中越來越重 要的部分。
                   

2. Path 與 Paths

                   java.nio.file.Path接口代表一個平台無關的平台路徑,描述了目 錄結構中文件的位置
         

                  Paths 提供的 get() 方法用來獲取 Path 對象:

                            Path     get(String first, String ... more) : 用於將多個字符串串連成路徑
               Path 常用方法:

                                 boolean  endsWith(String path) : 判斷是否以 path 路徑結束

                                 boolean startsWith(String path) :判斷是否以 path 路徑開始
                                 boolean isAbsolute() : 判斷是否是絕對路徑

                                 Path getFileName() : 返回與調用Path 對象關聯的文件名 
                                 Path getName(int idx) : 返回的指定索引位置 idx 的路徑名稱

                                 int getNameCount()  : 返回 Path 根目錄后面元素的數量
                                 Path getParent() :返回 Path 對象包含整個路徑,不包含 Path 對象指定的文件路徑

                                 Path getRoot() :返回調用 Path 對象的根路徑

                                 Path resolve(Path p) : 將相對路徑解析為絕對路徑

                                Path   toAbsolutePath() : 作為絕對路徑返回調用 Path 對象

                               String toString() : 返回調用 Path 對象的字符串表示形式
3.  Files 類

                    java.nio.file.Files 用於操作文件或目錄的工具類。

                            Files 常用方法:

                                               Path  copy(Path src,Path dest, CopyOption ... how) : 文件的復制
                                               Path  createDirectory(Path path,FileAttribute<?> ... attr) : 創建一個目錄

                                               Path   createFile(Path path,FileAttribute<?> ... arr) : 創建一個文件 
                                               void delete(Path path) : 刪除一個文件

                                                Pathmove(Path src, Path dest, CopyOption...how) : 將 src 移動到 dest 位置
                                                long size(Pathpath) : 返回 path 指定文件的大小Files 類 
                                                boolean exists(Path path,LinkOption ... opts) : 判斷文件是否存在
                                                boolean isDirectory(Path path, LinkOption ...opts) : 判斷是否是目錄
                                                boolean isExecutable(Path path) : 判斷是否是可執行文件

                                                booleanisHidden(Path path) : 判斷是否是隱藏文件
                                                boolean isReadable(Path path) : 判斷文件是否可讀 
                                                 boolean isWritable(Path path) : 判斷文件是否可寫

                                               boolean notExists(Path path,LinkOption ... opts) : 判斷文件是否不存在
                                                public static  A  <A extends BasicFileAttributes>   readAttributes(Path path,Class<A> type,LinkOption... options)  :

                                                 獲取與 path指定的文件相關聯的屬性 。
                   Files 常用方法: 用於操作內容

                                   SeekableByteChannel newByteChannel(Path  path, OpenOption...how) : 獲取與指定文件的連接, how 指定打開方式。
                                   DirectoryStream newDirectoryStream(Path path) : 打開 path 指定的目錄

                                   InputStream newInputStream(Path  path, OpenOption...how): 獲取 InputStream 對象

                                  OutputStream newOutputStream(Path path, OpenOption...how) : 獲取 OutputStream 對象自動 資源管理
       

    4.  Java 7 增加了一個新特性,該特性提供了另外      一種管理資源的方式,這種方式能自動關閉文 件。
               這個特性有時被稱為自動資源管理 (Automatic Resource Management, ARM) , 該特   性以 try 語句的擴展版為基礎。
                 自動資源管理 主要用於,當不再需要文件(或其他資源)時, 可以防止無意中忘記釋放它們。     

 

 

             自動 資源管理

                         自動資源管理基於 try 語句的擴展形式:
                                     try( 需要關閉的資源 聲明 ){

                                        // 可能發生異常的語句

                                       }catch( 異常類型 變量名 ){

                                       // 異常的處理語句

                                         }...... 
                                        finally{

                                        // 一定執行的語句 

                                        }

                             當 try 代碼塊結束時,自動釋放資源。因此不需要顯示的調用 close() 方法。該形式也稱為 “帶資源的 try 語句 ” 。
                           注意:

                                     ① try 語句中聲明的資源被隱式聲明為 final ,資源的作用局限於帶資源的 try 語句

                                     ② 可以在一條 try語句中管理多個資源,每個資源以 “;” 隔開即可 。
                                     ③需要關閉的資源,必須 實現 了 AutoCloseable 接口或其自接口 Closeable

package com.atguigu.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.DosFileAttributeView;

import org.junit.Test;

public class TestNIO_2 {
    
    
    //自動資源管理:自動關閉實現 AutoCloseable 接口的資源
    @Test
    public void test8(){
        try(FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
                FileChannel outChannel = FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.WRITE, StandardOpenOption.CREATE)){
            
            ByteBuffer buf = ByteBuffer.allocate(1024);
            inChannel.read(buf);
            
        }catch(IOException e){
            
        }
    }
    
    /*
        Files常用方法:用於操作內容
            SeekableByteChannel newByteChannel(Path path, OpenOption…how) : 獲取與指定文件的連接,how 指定打開方式。
            DirectoryStream newDirectoryStream(Path path) : 打開 path 指定的目錄
            InputStream newInputStream(Path path, OpenOption…how):獲取 InputStream 對象
            OutputStream newOutputStream(Path path, OpenOption…how) : 獲取 OutputStream 對象
     */
    @Test
    public void test7() throws IOException{
        SeekableByteChannel newByteChannel = Files.newByteChannel(Paths.get("1.jpg"), StandardOpenOption.READ);
        
        DirectoryStream<Path> newDirectoryStream = Files.newDirectoryStream(Paths.get("e:/"));
        
        for (Path path : newDirectoryStream) {
            System.out.println(path);
        }
    }
    
    /*
        Files常用方法:用於判斷
            boolean exists(Path path, LinkOption … opts) : 判斷文件是否存在
            boolean isDirectory(Path path, LinkOption … opts) : 判斷是否是目錄
            boolean isExecutable(Path path) : 判斷是否是可執行文件
            boolean isHidden(Path path) : 判斷是否是隱藏文件
            boolean isReadable(Path path) : 判斷文件是否可讀
            boolean isWritable(Path path) : 判斷文件是否可寫
            boolean notExists(Path path, LinkOption … opts) : 判斷文件是否不存在
            public static <A extends BasicFileAttributes> A readAttributes(Path path,Class<A> type,LinkOption... options) : 獲取與 path 指定的文件相關聯的屬性。
     */
    @Test
    public void test6() throws IOException{
        Path path = Paths.get("e:/nio/hello7.txt");
//        System.out.println(Files.exists(path, LinkOption.NOFOLLOW_LINKS));
        
        BasicFileAttributes readAttributes = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
        System.out.println(readAttributes.creationTime());
        System.out.println(readAttributes.lastModifiedTime());
        
        DosFileAttributeView fileAttributeView = Files.getFileAttributeView(path, DosFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
        
        fileAttributeView.setHidden(false);
    }
    
    /*
        Files常用方法:
            Path copy(Path src, Path dest, CopyOption … how) : 文件的復制
            Path createDirectory(Path path, FileAttribute<?> … attr) : 創建一個目錄
            Path createFile(Path path, FileAttribute<?> … arr) : 創建一個文件
            void delete(Path path) : 刪除一個文件
            Path move(Path src, Path dest, CopyOption…how) : 將 src 移動到 dest 位置
            long size(Path path) : 返回 path 指定文件的大小
     */
    @Test
    public void test5() throws IOException{
        Path path1 = Paths.get("e:/nio/hello2.txt");
        Path path2 = Paths.get("e:/nio/hello7.txt");
        
        System.out.println(Files.size(path2));
        
//        Files.move(path1, path2, StandardCopyOption.ATOMIC_MOVE);
    }
    
    @Test
    public void test4() throws IOException{
        Path dir = Paths.get("e:/nio/nio2");
//        Files.createDirectory(dir);
        
        Path file = Paths.get("e:/nio/nio2/hello3.txt");
//        Files.createFile(file);
        
        Files.deleteIfExists(file);
    }
    
    @Test
    public void test3() throws IOException{
        Path path1 = Paths.get("e:/nio/hello.txt");
        Path path2 = Paths.get("e:/nio/hello2.txt");
        
        Files.copy(path1, path2, StandardCopyOption.REPLACE_EXISTING);
    }
    
    /*
        Paths 提供的 get() 方法用來獲取 Path 對象:
            Path get(String first, String … more) : 用於將多個字符串串連成路徑。
        Path 常用方法:
            boolean endsWith(String path) : 判斷是否以 path 路徑結束
            boolean startsWith(String path) : 判斷是否以 path 路徑開始
            boolean isAbsolute() : 判斷是否是絕對路徑
            Path getFileName() : 返回與調用 Path 對象關聯的文件名
            Path getName(int idx) : 返回的指定索引位置 idx 的路徑名稱
            int getNameCount() : 返回Path 根目錄后面元素的數量
            Path getParent() :返回Path對象包含整個路徑,不包含 Path 對象指定的文件路徑
            Path getRoot() :返回調用 Path 對象的根路徑
            Path resolve(Path p) :將相對路徑解析為絕對路徑
            Path toAbsolutePath() : 作為絕對路徑返回調用 Path 對象
            String toString() : 返回調用 Path 對象的字符串表示形式
     */
    @Test
    public void test2(){
        Path path = Paths.get("e:/nio/hello.txt");
        
        System.out.println(path.getParent());
        System.out.println(path.getRoot());
        
//        Path newPath = path.resolve("e:/hello.txt");
//        System.out.println(newPath);
        
        Path path2 = Paths.get("1.jpg");
        Path newPath = path2.toAbsolutePath();
        System.out.println(newPath);
        
        System.out.println(path.toString());
    }
    
    @Test
    public void test1(){
        Path path = Paths.get("e:/", "nio/hello.txt");
        
        System.out.println(path.endsWith("hello.txt"));
        System.out.println(path.startsWith("e:/"));
        
        System.out.println(path.isAbsolute());
        System.out.println(path.getFileName());
        
        for (int i = 0; i < path.getNameCount(); i++) {
            System.out.println(path.getName(i));
            
        }
/*
true
true
true
hello.txt
nio
hello.txt
*/
    }
}
Files paths

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM