/**文件类,记录文件的各个属性*/
public class TxtFile {
public static void main(String[] args) {
TxtFile txtFile = new TxtFile("E:/Test.txt");
System.out.println(txtFile.readFile());
}
private String filePath;
public TxtFile(String filePath) {
this.filePath = filePath;
}
public StringBuffer readFile() {
return readFile(null);
}
public StringBuffer readFile(Object condition) {
File file = new File(filePath);
BufferedReader reader = null;
StringBuffer result = new StringBuffer();
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
double tempHeight = 0.0;
while ((tempString = reader.readLine()) != null) {
// 对每一行进行处理
result.append(tempString + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
public static void deleteFile(String path) {
File file = new File(path);
file.delete();
}
}
/** 合并多个文件 */
public class CompileFiles {
private String fileCatalog;
private String resultPath;
public static void main(String[] args) {
String fileCatalog = "E:/";// 文件目录
String resultPath = "E:/test.txt";
CompileFiles cf = new CompileFiles(fileCatalog, resultPath);
cf.compileTxtFiles();
}
public CompileFiles(String fileCatalog, String resultPath) {
this.fileCatalog = fileCatalog;
this.resultPath = resultPath;
}
/** 合并多个文件 */
public void compileTxtFiles() {
TxtFile.deleteFile(resultPath);// 清空结果文件
File file = new File(fileCatalog);
String[] paths = file.list();
ArrayList<String> txtList = new ArrayList<String>();
for (String path : paths) {
if (path.endsWith(".txt")) {
txtList.add(file.getAbsolutePath() + path);
}
}
compileTxtFiles(txtList, resultPath);
}
private void compileTxtFiles(List<String> filePathsList, String resultPath) {
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(resultPath,
true)));
List<TxtFile> fileList = new ArrayList<TxtFile>();
Map<TxtFile, Double> fileListMap = new HashMap<TxtFile, Double>();
Map<TxtFile, StringBuffer> fileContentMap = new HashMap<TxtFile, StringBuffer>();
while (fileListMap.size() > 0) {
for (int i = 0; i < fileList.size(); i++) {
TxtFile file = fileList.get(i);
// 处理每个文件的内容即可
out.print(file.readFile());
if (fileListMap.get(file) != null) {
fileListMap.remove(file);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
}