[简单]txt文件读写
下面的代码主要用于合并多个txt文件为一个,可能有更好的方法合并多个txt文件,代码如下:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Txt文件合并_S3_Test {
public static void main(String[] args) {
Txt文件合并_S3_Test t = new Txt文件合并_S3_Test();
t.mergeAllTextFile("F:/saveFile/temp/03隋唐五代文学");
}
public void mergeAllTextFile(String textFolderPath) {
File file = new File(textFolderPath);
if (!file.exists()) {
return;
}
try {
File[] files = getFileList(file);
List<File> fileList = Arrays.asList(files);
Collections.sort(fileList, new Comparator<File>() {
public int compare(File o1, File o2) {
if (o1.isDirectory() && o2.isFile())
return -1;
if (o1.isFile() && o2.isDirectory())
return 1;
return o1.getName().compareTo(o2.getName());
}
});
String outputPath = textFolderPath;
if (textFolderPath.indexOf("/") > -1) {
outputPath = textFolderPath.substring(textFolderPath.lastIndexOf("/"));
}
outputPath = new String(textFolderPath+ File.separator+ replaceStr(outputPath,"[^\u4e00-\u9fa5\u300a\u300b]", "")+ ".txt");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputPath), "utf-8"));
for (File f : fileList) {
String str = readFileContentToString(f);
bw.write(str, 0, str.length());
}
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private File[] getFileList(File file) {
FileFilter textFilter = new FileFilter() {
public boolean accept(File pathname) {
if ((pathname.isFile() && pathname.getName().endsWith(".txt")))
return true;
else
return false;
}
};
return file.listFiles(textFilter);
}
private String readFileContentToString(File file) {
BufferedReader reader = null;
StringBuffer sb = new StringBuffer();
sb.append("\r\n"+replaceStr(file.getName(),"[^\u300a\u300b\u4e00-\u9fa5\uFF00-\uFFEF]", "")+ "\r\n");
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "gbk"));
String content = null;
while ((content = reader.readLine()) != null) {
if (content.trim().length() > 0) {
content = replaceStr(content, "(@|#|\\$|&)", "");
sb.append(content + "\r\n");
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
private String replaceStr(String str, String pattern, String replaceStr) {
return new String(str.replaceAll(pattern, replaceStr));
}
}
结果为:
全文完。