• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

java 搞代码 4年前 (2022-01-05) 30次浏览 已收录 0个评论

这篇文章主要介绍了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:/学习资料/

来源gaodai.ma#com搞##代!^码网

笔记”),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;
 }
}

以上就是java文件操作工具类实现复制文件和文件合并的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:java文件操作工具类实现复制文件和文件合并

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址