Java Path與Files


Path和Files類封裝了在用戶機器上處理文件系統所需的所有功能,Path和Files是在Java SE 7 中新添加進來的類,使用時注意JDK版本。

        //在傳統java.io中, 文件和目錄都被抽象成File對象, 即 File file = new File(".");
        //NIO.中則引入接口Path代表與平台無關的路徑,文件和目錄都用Path對象表示
        //通過路徑工具類Paths返回一個路徑對象Path
        Path path = Paths.get("D:\\WorkFiles\\Project\\chitic-supplywater\\chitic-supplywater-common\\chitic-supplywater-common-api\\src\\main\\java\\com\\chitic\\supplywater\\common\\api\\util\\DateUtil.java");
        //一次性讀取
        List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
        StringBuilder sb = new StringBuilder();
        for(String line : lines){
            sb.append(line);
        }
        String fromFile = sb.toString();
        System.out.println(fromFile);
     //一行一行讀取文件
        Files.lines(path, StandardCharsets.UTF_8).forEach(System.err::println);

 

Path

Path表示的是一個目錄名序列,其后還可以跟着一個文件名。
注:文件系統的分隔符(類Unix文件系統是 / ,Windows是 \ )
路徑中的第一個部件可以是根部件,例如 / 或 C:\ 。以根部件開始的是絕對路徑;否則就是相對路徑。
方法:

static Path get(String first, String ... more)
通過連接給定的字符串創建一個路徑。
Path absolute = Paths.get("/Users/lujiafeng/Desktop/SpringBoot-Learning/Java_Test/src/cc.imi"); //絕對路徑
Path relative = Paths.get("src/cc.imi");  //相對路徑

 

注:在project中,相對路徑的根目錄是project的根文件夾

Path getParent()
返回父路徑,或者在該路徑沒有父路徑時,返回null。
Path getFileName()
返回該路徑的最后一個部件,或者在該路徑沒有任何部件時,返回null。
Path getRoot()
返回該路徑的根部件,或者在該路徑沒有任何根部件時,返回null。
讀寫文件
static byte[] readAllBytes(Path path)
讀入文件內容。
byte[] bytes = Files.readAllBytes(path);
//將文件當做字符串讀入,可添加如下代碼:
String content = new String(bytes, charset);
static List<String> readAllLines(Path path, Charset charset)
將文件當做行序列讀入。
List<String> lines = Files.readAllLines(path, charset);
static Path write(Path path, byte[] contents, OpenOption...options)
寫出一個字符串到文件中。
Files.write(path, content.getBytes(charset));
向指定文件中追加內容:

Files.write(path, content.getBytes(charset), StandardOpenOption.APPEND);
static Path write(Path path, Iterable<? extends CharSequence> contents, OpenOption options)
將一個行的集合寫出到文件中:
Files.write(path, lines);

注:以上方法適用於處理中等長度的文本文件,如果要處理的文件長度比較大,或者是二進制文件,那么還是應該使用流或者杜讀入器 / 寫出器。

復制、移動、刪除文件
static Path copy(Path from, Path to, CopyOption... options)
將文件從一個位置復制到另一個位置,並返回to。
Files.copy(fromPath, toPath);
static Path move(Path from, Path to, CopyOption... options)
將文件從一個位置移動到另一個位置,並返回to。如果目標路徑已經存在,那么復制或移動將失敗。
Files.move(fromPath, toPath);
static void delete(Path path)
刪除給定文件或空目錄,在文件或目錄不存在的情況下拋出異常。
static boolean deleteIfExists(Path path)
刪除給定文件或空目錄。在文件或目錄不存在的情況下返回false。
創建文件和目錄
創建新目錄:
Files.createDirectory(path);
創建一個空文件
Files.createFile(path);

 

獲取文件信息
  • static boolean exists(Path path)
  • static boolean isHidden(Path path)
  • static boolean isReadable(Path path)
  • static boolean isWriter(Path path)
  • static boolean isExecutable(Path path)

https://blog.csdn.net/oMaoYanEr/article/details/80961130


免責聲明!

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



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