Java中FileInputStream和FileOutputStream类实现文件夹及文件的复制粘贴
生活随笔
收集整理的這篇文章主要介紹了
Java中FileInputStream和FileOutputStream类实现文件夹及文件的复制粘贴
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
基本思路就是邊搜索邊復制,這里用的是廣度搜索(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 目標文件* @param f2 復制到的目標* @throws IOException*/private static void getPathBFS(File f1,File f2) throws IOException {//運用隊列進行廣度搜索ArrayDeque<File> deque = new ArrayDeque<File>();//用于存儲復制目標文件ArrayDeque<File> dequeCopy = new ArrayDeque<File>();//第一個File實例入隊 deque.offer(f1);//創建第一個文件夾f2 = new File(f2,f1.getName());dequeCopy.offer(f2);//隊列為空時停止while(!deque.isEmpty()){//取隊頭File[] ff = deque.peek().listFiles();File copyFiledir = dequeCopy.peek();//創建文件夾 copyFiledir.mkdir();//出隊 deque.poll();dequeCopy.poll();for(int i=0;i<ff.length;i++){//如果是目標文件夾入隊if(ff[i].isDirectory()){//復制文件夾入隊File temp = new File(copyFiledir,ff[i].getName());dequeCopy.push(temp);deque.push(ff[i]);}else{//復制到相應文件夾copyFile(ff[i],copyFiledir.getAbsolutePath()+"\\"+ff[i].getName());}}}}}?
轉載于:https://www.cnblogs.com/hnzyyTl/p/4970104.html
總結
以上是生活随笔為你收集整理的Java中FileInputStream和FileOutputStream类实现文件夹及文件的复制粘贴的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 58同城家政服务公司
- 下一篇: 唯品会app怎么解绑银行卡(汉典唯字的基