難度在與怎麼同步複制檔案路徑 可以同樣利用遞歸檔案夾的方式,把将要遞歸的路徑在進行遞歸,然後每次進行更新。
附源碼
package cn.edu.shengda;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
*
* 檔案以及檔案夾的拷貝
* @author 書生
*
*/
public class Test5_copy {
public static void main(String[] args) {
// copy_File("abc.txt", "def.txt");
File file = new File("G:\\Java_Study\\IO流_01");// 讀入檔案夾
mkdirs_Wenjian(file, "G:\\java_Study\\IO流_copy");// 後一個為要寫入的檔案路徑
}
public static void mkdirs_Wenjian(File file, String writesrc) { // 檔案夾的複制
if (file == null || !file.exists()) { // 如果檔案不存在 或檔案 為空 跳出
return;
}
if (file.isFile()) { // 如果是檔案
String str = writesrc + '\\' + file.getName(); // 修改将要寫入的檔案夾路徑
File readFile = new File(str); // 将要寫入的路徑
InputStream os = null; // 輸入源
OutputStream is = null; // 輸出源
try {
os = new FileInputStream(file);
is = new FileOutputStream(readFile);
byte [] temp = new byte[1024]; // 存放位元組
int len = -1;
while ((len = os.read(temp)) != -1) { // 讀取資料
is.write(temp, 0, len); // 将讀入的資料進行寫入
is.flush(); // 重新整理
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally { // 關閉輸入輸出流
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (file.isDirectory()) { // 如果是檔案夾
String str = writesrc + '\\' + file.getName(); // 将要寫入的路徑
File kk = new File(str);
kk.mkdirs(); // 建立将要寫入路徑沒有得檔案夾
File [] flag = file.listFiles(); // 将檔案夾裡的檔案放入一個清單
for (File tempFile : flag) { // 周遊
mkdirs_Wenjian(tempFile, str); // 遞歸 傳入要讀入的路徑,同步更新要寫入的路徑
}
}
}
public static void copy_File(String readsrc, String writesrc) { // 複制檔案 同上
File readFile = new File(readsrc);
File writeFile = new File(writesrc);
InputStream iStream = null;
OutputStream oStream = null;
try {
iStream = new FileInputStream(readFile);
oStream = new FileOutputStream(writeFile);
int len = -1;
byte [] datas = new byte[1024];
while ((len = iStream.read(datas)) != -1) {
oStream.write(datas, 0, len);
// String str = new String(datas, 0, len);
// System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (oStream != null) {
oStream.close();
}
}catch (IOException e) {
e.printStackTrace();
}
try {
if (iStream != null) {
iStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}