Java中FileInputStream和FileOutputStream类实现文件夹及文件的复制粘贴
生活随笔
收集整理的這篇文章主要介紹了
Java中FileInputStream和FileOutputStream类实现文件夹及文件的复制粘贴
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
基本思路就是邊搜索邊復(fù)制,這里用的是廣度搜索(BFS)
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; 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; import java.util.ArrayDeque;public class CopyFile {public static void main(String[] args) {File f1 = new File("kkk");File f2 = new File("D:\\");try {getPathBFS(f1,f2);} catch (IOException e) {// TODO Auto-generated catch block e.printStackTrace();}}/*** 用于讀和寫* @param f1 輸入流* @param f2 輸出流*/private static void copyFile(File f1,String f2){InputStream in = null;OutputStream out = null;try {in = new BufferedInputStream(new FileInputStream(f1));out = new BufferedOutputStream(new FileOutputStream(f2));byte by[] = new byte[1024];int len = 0;while((len = in.read(by))!=-1){out.write(by, 0, len);}} catch (FileNotFoundException e) {e.printStackTrace();}catch (IOException e) {// TODO Auto-generated catch block e.printStackTrace();}finally{if(in!=null){try {in.close();} catch (IOException e) {// TODO Auto-generated catch block e.printStackTrace();}}if(out != null){try {out.close();} catch (IOException e) {// TODO Auto-generated catch block e.printStackTrace();}}}}/*** 用于搜索* @param f1 目標(biāo)文件* @param f2 復(fù)制到的目標(biāo)* @throws IOException*/private static void getPathBFS(File f1,File f2) throws IOException {//運(yùn)用隊(duì)列進(jìn)行廣度搜索ArrayDeque<File> deque = new ArrayDeque<File>();//用于存儲(chǔ)復(fù)制目標(biāo)文件ArrayDeque<File> dequeCopy = new ArrayDeque<File>();//第一個(gè)File實(shí)例入隊(duì) deque.offer(f1);//創(chuàng)建第一個(gè)文件夾f2 = new File(f2,f1.getName());dequeCopy.offer(f2);//隊(duì)列為空時(shí)停止while(!deque.isEmpty()){//取隊(duì)頭File[] ff = deque.peek().listFiles();File copyFiledir = dequeCopy.peek();//創(chuàng)建文件夾 copyFiledir.mkdir();//出隊(duì) deque.poll();dequeCopy.poll();for(int i=0;i<ff.length;i++){//如果是目標(biāo)文件夾入隊(duì)if(ff[i].isDirectory()){//復(fù)制文件夾入隊(duì)File temp = new File(copyFiledir,ff[i].getName());dequeCopy.push(temp);deque.push(ff[i]);}else{//復(fù)制到相應(yīng)文件夾copyFile(ff[i],copyFiledir.getAbsolutePath()+"\\"+ff[i].getName());}}}}}?
轉(zhuǎn)載于:https://www.cnblogs.com/hnzyyTl/p/4970104.html
總結(jié)
以上是生活随笔為你收集整理的Java中FileInputStream和FileOutputStream类实现文件夹及文件的复制粘贴的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 58同城家政服务公司
- 下一篇: 唯品会app怎么解绑银行卡(汉典唯字的基