1. 程式人生 > >java 複製資料夾到指定目錄

java 複製資料夾到指定目錄

好久之前學得了,當時實現了還激動的不得了。今天再拿起來 發現忘記了不少,沒辦法專案需要,又對流了解了下,古人說的沒錯啊,果然溫故而知新,看來還是要常回頭啊。

下面說下 複製資料夾的重難點(其實不是太難了,給我個裝大神的機會吧,哈哈)

當然了,首先 肯定是要對IO流有一定的瞭解,不然看程式碼會很懵逼的。其次 是對邏輯要有一定的概念,就是對資料夾和檔案的不同處理方式。這個我就在這裡說下 資料夾要進行回撥處理(新手看程式碼可能會覺得,資料夾執行一半時再回調執行子資料夾,這樣為什麼到頭來還會把父資料夾中未處理的處理完成。哈哈,這就是回撥函式的魅力啊,好好看看吧,很神奇的),檔案的話 就是直接建立流進行讀寫操作,在這裡要了解BufferedInputStream、BufferedOutputStream用於不用的特點以及和FileInputStream、FileOutputStream之間的關係。讀寫的操作都是固定的,記住就好,當然理解更好了,可以長久記憶(畢竟強行記憶不是咱智商優勢程式設計師的風格)。最後 也是很重要的一點,千萬不要忘記關閉流(不關的話,結果會令你哭泣)


廢話不多說,用碼說話:

package com.tpad.copydir;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.JOptionPane;

public class CopyDir {

public static void main(String[] args) throws IOException {

// TODO Auto-generated method stub
long startTime = System.currentTimeMillis(); // 開始執行的時間
String srcDirFullPath = "d:\\floder";
String dstDirFullPath = "e:\\copy_flode\\a\\b\\c";

try {
CopyDir copydir = new CopyDir();
copydir.CopyFloder(srcDirFullPath, dstDirFullPath);
JOptionPane.showMessageDialog(null, "ok");
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}

long endTime = System.currentTimeMillis(); // 執行完的時間
long useTime = endTime - startTime; // 執行復制資料夾用的時間(毫秒)
System.out.println("完成複製共用" + useTime + "毫秒");
}

public void CopyFloder(String srcDirFullPath, String dstDirFullPath) throws IOException {
// TODO Auto-generated method stub
File srcFile = new File(srcDirFullPath);
File dstFile = new File(dstDirFullPath);

File[] file = srcFile.listFiles(); // 獲取檔案目錄內的檔案個數

// 目標檔案是否存在
if (!dstFile.exists()) {
if (dstFile.mkdirs() == false) { // 這裡是先建立然後驗證是否建立成功,成功 true  失敗 false
throw new IOException(dstFile.getPath() + " (The source file creation failed)"); // 失敗 給使用者提示
}
}
// 遍歷
for (File newFile : file) {
if (newFile.isDirectory()) {
// 資料夾
File sendFloderFile = new File(dstFile, newFile.getName());
// 在目標地址建立資料夾
if (!sendFloderFile.exists()) {
if (sendFloderFile.mkdir() == false) {
throw new IOException(sendFloderFile + " (File creation failed)");
}
}
// 回撥, 即子資料夾進行處理
CopyFloder(newFile.toString(), sendFloderFile.toString());
} else {
// 檔案
File sendWordFile = new File(dstFile, newFile.getName());
CopyWord(newFile.toString(), sendWordFile.toString());
}
}
}

// 對檔案進行讀寫操作
public void CopyWord(String srcDirFullPath2, String dstDirFullPath2) throws IOException {
// TODO Auto-generated method stub
File srcFile2 = new File(srcDirFullPath2);
File dstFile2 = new File(dstDirFullPath2);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile2));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dstFile2));
int ch = 0;
byte[] byteArray = new byte[1024];
while ((ch = bis.read(byteArray)) != -1) {
bos.write(byteArray, 0, ch);
}
bos.close();
bis.close();
}
}

有錯誤,歡迎大家指正哈,共同進步