java檔案操作工具類實現複製檔案和檔案合并_java

來源:互聯網
上載者:User

兩個方法:
1、複製一個目錄下面的所有檔案和檔案夾
2、將一個檔案目錄下面的所有文字檔合并到同一個檔案中

複製代碼 代碼如下:

package com.firewolf.test;

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

public class FileReaderUtil {
 public static void main(String[] args){
  try {
   //mergeFile(new File("C:/Documents and Settings/liuxing0/案頭/建立檔案夾/script"), new File("D:/all.sql"));
   copyFiles(new File("G:/學習資料/筆記"),new File("G:/Test"));
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

 /**
  * 拷貝某個檔案目錄下面的所有檔案,
  * @param sourcePath 原檔案目錄
  * @param desPath 目的檔案目錄
  */
 private static void copyFiles(File sourceFile,File desFile) throws IOException{
  if(sourceFile.isFile()){
   File file = new File(desFile.getPath()+"/"+sourceFile.getName());
   FileInputStream fis = new FileInputStream(sourceFile);
   FileOutputStream fos = new FileOutputStream(file);
   int len = 0;
   byte[] buf = new byte[1024];
   while((len = fis.read(buf)) != -1)
    fos.write(buf,0,len);
  }else{
   File dir = new File(desFile.getPath()+"/"+sourceFile.getName());
   if(!dir.exists())
    dir.mkdir();
   String[] names = sourceFile.list();
   for (int i = 0; i < names.length; i++) {
    copyFiles(new File(sourceFile.getPath()+"/"+names[i]),dir);
   }
  }
 }

 /**
  * 將一個檔案目錄下面的所有檔案獨到一個檔案中的方法(主要用於將很多文字檔合并到一起)
  * @param sourceFile
  * @param decFile
  * @return
  * @throws IOException
  */
 private static File mergeFile(File sourceFile,File decFile) throws IOException{
  String[] fileList = sourceFile.list();
  for (String string : fileList) {
   File file = new File(sourceFile.getPath()+"/"+string);
   if(!file.isDirectory()){

    FileInputStream fis = new FileInputStream(file);
    FileOutputStream fos = new FileOutputStream(decFile, true);
    byte[] buffer = new byte[1024];
    int len = 0;
    while((len= fis.read(buffer)) != -1)
     fos.write(buffer, 0, len);
   }
   else {
    decFile = mergeFile(file,decFile);
   }
  }
  return decFile;
 }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.