1. 程式人生 > >NIO的檔案操作Path和File

NIO的檔案操作Path和File

Path

path介面是在java7加入到NIO的,位於java.nio.file包,它的例項代表了檔案系統裡的一個路徑。java中的Path表示檔案系統的路徑。可以指向檔案或資料夾。也有相對路徑和絕對路徑之分。絕對路徑表示從檔案系統的根路徑到檔案或是資料夾的路徑。相對路徑表示從特定路徑下訪問指定檔案或資料夾的路徑。
初始化

Path path = Paths.get("D:\\svn-config.properties");
Path.normalize()

為了使用java.nio.file.Path例項,必須首先建立它。可以使用Paths類的靜態方法Paths.get()來產生一個例項。
normalize()

方法可以標準化一個路徑,就是移除掉所有在路徑字元中的的 . 和 ..,同時決定路徑字串指向哪條路徑.

Path path = Paths.get("D:\\Users\\xxx\\Desktop\\..\\svn-config.properties");
Path path1 = path.normalize();
System.out.println(path);
System.out.println(path1);

結果:

D:\Users\xxx\Desktop\..\svn-config.properties 
D:\Users\xxx\svn-config.properties 

java NIO Path類也能使用相對路徑。可以通過Paths.get(basePath, relativePath)建立一個相對路徑Path。示例如:

Path projects = Paths.get("d:\\data", "projects");
Path file = Paths.get("d:\\data", "projects\\a-project\\myfile.txt");

Files

Java NIO File 類提供了幾個在檔案系統中熟練操作檔案的方法

  • 判斷檔案存在

LinkOption.NOFOLLOW_LINKS 表明判斷檔案存在的方法不應該根據檔案系統中的符號連線來判斷路徑是否存在

 Path path = Paths.get("D:\\Users\\xxx\\Desktop\\svn-config.properties");
 boolean isExist = Files.exists(path, LinkOption.NOFOLLOW_LINKS);
  • 建立資料夾
Path path = Paths.get("D:\dir");
try 
{
    Path newDir = Files.createDirectory(path);
} catch(FileAlreadyExistsException e){
    // the directory already exists.
} catch (IOException e) {
    //something else went wrong
    e.printStackTrace();
}
  • 拷貝檔案
Path sourcePath      = Paths.get("data/logging.properties");
Path destinationPath = Paths.get("data/logging-copy.properties");

try {
    Files.copy(sourcePath, destinationPath);
} catch(FileAlreadyExistsException e) {
    //destination file already exists
} catch (IOException e) {
    //something else went wrong
    e.printStackTrace();
}
  • 覆蓋檔案
Path sourcePath      = Paths.get("data/logging.properties");
Path destinationPath = Paths.get("data/logging-copy.properties");

try {
    Files.copy(sourcePath, destinationPath,
            StandardCopyOption.REPLACE_EXISTING);
} catch(FileAlreadyExistsException e) {
    //destination file already exists
} catch (IOException e) {
    //something else went wrong
    e.printStackTrace();
}
  • 移動檔案
Path sourcePath      = Paths.get("data/logging-copy.properties");
Path destinationPath = Paths.get("data/subdir/logging-moved.properties");

try {
    Files.move(sourcePath, destinationPath,StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    //moving file failed.
    e.printStackTrace();
}
  • 刪除檔案
Path path = Paths.get("data/subdir/logging-moved.properties");
try {
    Files.delete(path);
} catch (IOException e) {
    //deleting file failed
    e.printStackTrace();
}
  • 遍歷資料夾
Path path = Paths.get("D:\\mnt");
Files.walkFileTree(path, new FileVisitor<Path>() {
    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
        System.out.println("pre visit dir:" + dir);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        System.out.println("visit file: " + file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
        System.out.println("visit file failed: " + file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
        System.out.println("post visit directory: " + dir);
        return FileVisitResult.CONTINUE;
    }
});
  • 查詢檔案
 Path root = Paths.get("D:\\mnt");
 final String fileToFind = File.separator+"path.txt";
 try {
     Files.walkFileTree(root, new SimpleFileVisitor<Path>() {

         @Override
         public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
             String fileString = file.toAbsolutePath().toString();
             //System.out.println("pathString = " + fileString);

             if(fileString.endsWith(fileToFind)){
                 System.out.println("file found at path: " + file.toAbsolutePath());
                 return FileVisitResult.TERMINATE;
             }
             return FileVisitResult.CONTINUE;
         }
     });
 } catch(IOException e){
     e.printStackTrace();
 }
  • 迴圈刪除檔案
Path rootPath = Paths.get("data/to-delete");

try {
  Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
      System.out.println("delete file: " + file.toString());
      Files.delete(file);
      return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
      Files.delete(dir);
      System.out.println("delete dir: " + dir.toString());
      return FileVisitResult.CONTINUE;
    }
  });
} catch(IOException e){
  e.printStackTrace();
}
  • 生成超連結
//連線路徑
 Path p = Paths.get("D:\\mnt\\1.txt");
 //目標路徑
 Path target = Paths.get("D:\\Users\\weizhiming\\Desktop");
 //生成指向目標路徑的超連結,返回連線路徑p
 Path p3 = Files.createSymbolicLink(p,target);
  • 讀取檔案內容
//讀取每行資料放入List中
List<String> lines = Files.readAllLines(Paths.get("d://a.txt"));
//讀取檔案內容放入流中
Stream<String> lines = Files.lines(Paths.get("d://a.txt"));