在如今的功能需求中,文件的處理基本上都是會涉及到的,應該說是一個很經常使用的功能
public static void main(String[] args) throws IOException {
String url = "test.txt";
String suffixName = url.substring(url.lastIndexOf("."));
//獲取要複製的文件路徑
FileInputStream fileInputStream = new FileInputStream("F:\\" + url);
String filePath = "F:\\test\\";
File dest = new File(filePath+System.currentTimeMillis());
// 判斷文件路徑是否存在,不存在就建立路徑
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdir();
}
//獲取要寫入的文件路徑
FileOutputStream fileOutputStream = new FileOutputStream(dest + suffixName);
//獲取要複製的的文件通道
FileChannel fileChannelInput = fileInputStream.getChannel();
//獲取要寫入的文件通道
FileChannel fileChannelOutput = fileOutputStream.getChannel();
// 將要複製文件通道的數據,寫入到要寫入的文件通道
fileChannelInput.transferTo(0, fileChannelInput.size(), fileChannelOutput);
try {
if (fileInputStream != null){
fileInputStream.close();
}
if (fileChannelInput != null) {
fileChannelInput.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
if (fileChannelOutput != null) {
fileChannelOutput.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
複製代碼