檔案拷貝案例
阿新 • • 發佈:2020-08-29
用到的知識點有:FileInputStream、FileOutputStream、File物件的常用方法、重點是遞迴方法和路徑的拼接。
package com.yc.day0829;
import java.io.*;
/**
* @program: javaSE
* 描述:
* 將D:\\aa檔案全部copy到c盤中
* @author: yc
* @create: 2020-08-29 15:28
**/
public class CopyTest {
public static void main(String[] args) {
//拷貝源和拷貝目標的路徑都是可能改變的。
File srcFile = new File("D:\\aa"); //拷貝源
File destFile = new File("c:\\"); //拷貝目標
copyDir(srcFile,destFile); //呼叫方法拷貝
}
private static void copyDir(File srcFile, File destFile) {
if(srcFile.isFile()){ //源File物件是檔案的話,就將檔案進行I/o讀寫操作。
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(srcFile);
//這裡使用endwith()方法是因為路徑尾部有可能沒有帶“\”,可能程式會出錯。
String path = (destFile.getAbsolutePath().endsWith("\\")?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\\")
+srcFile.getAbsolutePath().substring(3); //這裡的3是根據你的拷貝源的需求來擷取的。path是拷貝目標下檔案的路徑。
fos = new FileOutputStream(path); //建立fos物件的同時也會在指定路徑的硬碟上生成檔案。初學者疑惑的地方
byte[] bytes = new byte[1024*1024];
int c = 0;
while((c = fis.read(bytes))!= -1){
fos.write(bytes,0,c);
}
fos.flush(); //重新整理
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return; //如果是一個檔案的話,遞迴結束
}
//獲取源下面的子目錄
File[] files = srcFile.listFiles();
for (File file : files) {
if(file.isDirectory()){
//新建對應的目錄
String srcDir = file.getAbsolutePath();
String destDir = (destFile.getAbsolutePath().endsWith("\\")?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\\")
+srcDir.substring(3); //destDir是拷貝目標下的資料夾的路徑。
File newFile = new File(destDir);
if(!newFile.exists()){ //File物件如果不存在,就建立多級資料夾。
newFile.mkdirs();
}
}
//遞迴
copyDir(file,destFile); //重點理解。
}
}
}