最近在使用文件流相关的API,写一个文章防止以后忘记:
首先导入jar包:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
通过遍历可以复制指定文件夹下面的所有文件和文件夹到指定目录(其中当然可以修改一些数据,暂时不加上去了):
/**
* @Description: TODO
* @ClassName: ChangeAndTransFiles
* @author: guojin
* @date: 2019年2月24日 下午2:47:27
*/
public class ChangeAndTransFiles {
final static String dir1="C:\\Users\\guojin\\Desktop\\FileRev\\Desktop\\java";
final static String dirs=ChangeAndTransFiles.class.getResource("/").getPath();
public static void main(String[] args) throws IOException {
String fpath="com.java";
String rpath = getSeparatorReplace(fpath,".", File.separator);
String toDirs=dirs.substring(0,dirs.indexOf("/WebContent"))+File.separator+"src";
System.out.println(toDirs);
File file = new File(dir1);
File dirs1 = new File(dirs,rpath);
changeFile(file, dirs1);
}
/**
* 复制文件夹的文件
* @Title: changeFile
* @return void
* @version v1.0.0
* @author guojin
* @date 2019年2月28日下午4:33:00
* @param from
* @param todirs
* @throws IOException
*/
private static void changeFile(File from, File todirs) throws IOException {
if(!todirs.exists()) {
todirs.mkdirs();
}
if(from.exists()) {
String[] list = from.list();
for (String string : list) {
// System.out.println(string);
File fromfile = new File(from,string);
if(fromfile.exists()) {
if(fromfile.isFile()) {
tranData(todirs, string, fromfile);
System.out.println("已完成:"+string);
}else if (fromfile.isDirectory()) {
//遍历
changeFile(fromfile, new File(todirs,string));
System.out.println("文件夹已完成:"+string);
}
}else {
//文件不存在
}
}
//循环完成
}else {
//目录不存在
}
}
/**
* 复制两个文件的内容
* @Title: tranData
* @return void
* @version v1.0.0
* @author guojin
* @date 2019年2月28日下午4:32:43
* @param todirs
* @param topath
* @param ffile
* @throws IOException
*/
private static void tranData(File todirs, String topath, File ffile) throws IOException {
File tofile = new File(todirs,topath);
if(!tofile.exists()) {
tofile.createNewFile();
}
FileReader rf = new FileReader (ffile);
BufferedReader br = new BufferedReader(rf);
//加true,表示再原来的基础上追加内容,默认false即每次读入就把之前的内容清空再读入。
//UTF-8是编码方式
BufferedWriter wr=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tofile,false), "GBK"));
IOUtils.copyLarge(br, wr);
br.close();
wr.flush();
wr.close();
}
/**
* 循环替换字符串中的指定字符串,类似于replaceAll(因为使用replaceAll方法替换/时会有问题)
* @Title: getSeparatorReplace
* @return String
* @version v1.0.0
* @author guojin
* @date 2019年2月28日下午4:29:00
* @param rootPath
* @param reg
* @param separator
* @return
*/
private static String getSeparatorReplace(String rootPath, String reg, String separator) {
String rPath=rootPath;
String roote="";
int index=-1;
int i = rPath.indexOf(reg);
for (; i !=-1; i=rPath.indexOf(reg, i+1)) {
roote += rPath.substring(index+1,i);
roote +=separator;
index=i;
}
if(i==-1 && (index+1<rPath.length())) {
roote += rPath.substring(index+1,rPath.length());//将最后的后缀加上
}
return roote;
}
}