当前位置: 移动技术网 > IT编程>开发语言>Java > java文件操作工具类实现复制文件和文件合并

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网