国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java文件操作工具類實現復制文件和文件合并

2019-11-26 15:38:37
字體:
來源:轉載
供稿:網友

兩個方法:
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;
 }
}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 监利县| 巴林左旗| 绥阳县| 固原市| 富平县| 柏乡县| 瑞金市| 宝清县| 华安县| 贺州市| 灌云县| 宜兰市| 赤峰市| 遵义市| 临邑县| 遂宁市| 新绛县| 上栗县| 牙克石市| 平塘县| 黄冈市| 南陵县| 博乐市| 布拖县| 临桂县| 曲松县| 霍城县| 尼勒克县| 客服| 四会市| 洛扎县| 海口市| 旬邑县| 平泉县| 贵州省| 资源县| 吉木萨尔县| 八宿县| 榆中县| 建瓯市| 济阳县|