用Java實現將多級檔案夾下的所有檔案統一放到一個檔案夾中

來源:互聯網
上載者:User

標籤:tor   main   pack   file   string   fileinput   判斷   遞迴調用   檔案   

每次下了電影(男生懂得呦),每部電影都放在一個單獨的檔案夾裡,看的時候很是不方便啊,一直重複著進入檔案夾、後退,再進、再退的操作,而手動把這些電影全部複製出來又太繁瑣。因此為瞭解決這個問題,用IO寫了一個小工具。

以下代碼只實現了把多級檔案夾下的所有檔案複製到一個檔案夾中,如果需要指定複製檔案的格式,可以在1111處添加一個判斷。如果需要同時刪除原檔案夾可以在添加一個遞迴刪除的方法。

package Bao;

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


public class CopyFolderDemo {
public static void main(String[] args) throws IOException {
// 封裝資料來源File
File srcFile = new File("d:\\檔案夾名字");    //這裡填源檔案夾路徑

copyFolder(srcFile);
//copyFile(srcFile);
}

private static void copyFolder(File srcFile)
throws IOException {
// 判斷該File是檔案夾還是檔案
File[] ff=srcFile.listFiles();
for(File f:ff){

//如果是檔案夾,則遞迴調用
if(f.isDirectory()){
copyFolder(f);
}else{               ///11111

//如果是檔案則複製
copyFile(f);
//System.out.println(f.getName());


}
}
}
//用位元組緩衝流實現檔案複製
private static void copyFile(File srcFile) throws IOException {

File destFile = new File("d:\\檔案夾名字",srcFile.getName());   //這裡寫目的檔案夾路徑
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
srcFile));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(destFile));

byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}

bos.close();
bis.close();
}
}

用Java實現將多級檔案夾下的所有檔案統一放到一個檔案夾中

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.