import java.io.*;
public class ReadFiel {
//要导出数据到这个文件
private static String filePath = "E:\\test.doc";
public static void main(String[] args) {
// 传入java的路径
readJavaToTxt("E:\\IDEAProject\\test");
}
public static void readJavaToTxt(String path) {
File file = new File(path); //获取其file对象
func(file);
}
private static void func(File file){
File[] fs = file.listFiles();
for(File f:fs){
if(f.isDirectory()) {//若是目录,则递归打印该目录下的文件
func(f);
}
if(f.isFile()) {
String fileName = f.getName();
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
if(suffix.equals("java")) {
readFile(f);
}
}
}
}
private static void readFile(File file) {
// String path = "c:\\hello.txt";
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream,"UTF-8"));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
//System.out.println(line);
saveAsFileWriter(line+"\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(fileInputStream != null){
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void saveAsFileWriter(String content) {
Writer fwriter = null;
try {
// true表示不覆盖原来的内容,而是加到文件的后面。若要覆盖原来的内容,直接省略这个参数就好
//fwriter = new FileWriter(filePath, true);
fwriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath,true),"UTF-8"));
fwriter.write(content);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
fwriter.flush();
fwriter.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
编译:javac ReadFiel.java
运行:java ReadFiel