C:\data\StudentInfo.txt
--------
C:\data\新建 文本文檔.txt
(該文件內容為空!)
C:\data\新建文件夾\1.txt
第壹行
第二行
代碼如下:
import java.io.*;
public class AllTxt {
public static void main(String[] args) {
moveAllContentToOne("C:\\data\\", "C:\\all.txt");
}
public static void moveAllContentToOne(String path, String target) {
File source = new File(path);
File targetfile = new File(target);
moveAllContentToOne(source, targetfile);
}
public static void moveAllContentToOne(File source, File targetfile) {
File[] files = null;
if(source.isDirectory()) {
files = source.listFiles();
for(int i=0; i<files.length; i++) {
moveAllContentToOne(files[i], targetfile);
}
return;
}
if(source.getName().matches(".*\\.[tT][xX][tT]$")) {
System.out.println(source.getName());
try {
BufferedReader br = new BufferedReader(new FileReader(source));
BufferedWriter bw = new BufferedWriter(new FileWriter(targetfile, true));
bw.write(source.getPath());
bw.newLine();
String str = br.readLine();
if(str == null) {
bw.write("(該文件內容為空!)");
bw.newLine();
}
else {
while(str != null) {
bw.write(str);
bw.newLine();
str = br.readLine();
}
}
bw.newLine();
bw.flush();
bw.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}