栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java文件操作工具类实现复制文件和文件合并

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java文件操作工具类实现复制文件和文件合并

两个方法:
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();
  }
 }

 
 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);
   }
  }
 }

 
 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;
 }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/152395.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号