只需按照自己的需求修改 input和output的路径即可
import java.io.*;
public class SoftFileTest {
public static void main(String[] args) throws IOException {
File input = new File("D:\\项目开发\\实验室项目");
File output = new File("D:\\code.txt");
if(!output.exists()){
output.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(output));
StringBuffer sb = new StringBuffer();
loopRead(input,sb);
write(sb.toString(),bw);
}
private static String readFileToString(File file) {
BufferedReader bf = null;
StringBuilder sb = new StringBuilder();
try {
bf = new BufferedReader(new FileReader(file));
String line;
while ((line = bf.readLine()) != null) {
String s = line.trim();
if (s.length() == 0) {
continue;
}
if (s.startsWith("/") || s.startsWith("*")) {
continue;
}
sb.append(line);
sb.append("\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bf != null) {
bf.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
private static void loopRead(File dir, StringBuffer sb) {
File[] files = dir.listFiles();
if (files != null) {
for(File file:files){
if(file.isDirectory()){
loopRead(file,sb);
}
else if (file.length()!=0&&file.isFile()&&file.getName().endsWith(".java")){
sb.append(readFileToString(file));
}
}
}
}
private static void write(String str,BufferedWriter bw){
try {
bw.write(str);
} catch (Exception e) {
e.printStackTrace();
}
finally {
try{
if(bw!=null){
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}