Files類的使用
java nio包中Files類的使用,從jdk1.7引入的,下面是簡單使用例子說明。
1.判斷文件是否存在、拷貝文件
package com.test.file;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class TestCopyFile {
public static void main(String[] args) {
String source = "D:\\freestyle\\SJZT\\ODS\\copytest.txt";
String dest = "D:\\freestyle\\share_files\\download\\bankStaffInfo\\copytest.txt";
boolean b1 = new File(source).exists();
System.out.println("文件是否存在:" + b1);
/*
* 判斷文件是否存在
*
* LinkOption可以不傳,它代表的是"鏈接選項"
* 這個參數主要用于指示方法在檢查文件是否存在時,如何處理符號鏈接。它是一個特殊的文件,指向另一個文件或目錄。
* 如果不傳linkOption則默認是跟蹤符號鏈接的。它檢查的不是符號鏈接文件本身是否存在,而是它所指向的目標是否存在。
* LinkOption只有一個枚舉值:NOFOLLOW_LINKS,表示不跟隨符號鏈接。它只檢查給定的路徑符號鏈接文件本身是否存在,而完全不關心它指向什么。
*
* 補充:
* 非符號鏈接文件:如果你檢查的路徑不是一個符號鏈接,而是一個普通文件或目錄,那么無論是否傳遞 LinkOption.NOFOLLOW_LINKS,
* 結果都是一樣的,都是檢查該普通文件或目錄本身是否存在。
*
*/
boolean b2 = Files.exists(Paths.get(source));
System.out.println("文件是否存在:" + b2);
boolean success = copy(source, dest);
System.out.println("文件拷貝結果:" + success);
}
/**
* 拷貝文件
*
* @param sourcePath
* @param destPath
* @return
*/
public static boolean copy(String sourcePath, String destPath) {
try {
Path source = Paths.get(sourcePath);
Path destination = Paths.get(destPath);
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
}
上面Files.copy如果目標文件的父路徑文件夾不存在時,會報錯,優化成如下:
/**
* 拷貝文件
*
* @param sourcePath
* @param destPath
* @return
*/
public static boolean copy(String sourcePath, String destPath) {
try {
Path source = Paths.get(sourcePath);
Path destination = Paths.get(destPath);
Path parentDestination = destination.getParent();
if (parentDestination != null && !Files.exists(parentDestination)) {
Files.createDirectories(parentDestination);
System.out.println("directory not exist, create:" + parentDestination + " success");
}
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
--
浙公網安備 33010602011771號