运行结果
源码
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class WalkFiles {
// 以java、jsp为后缀的文件
static final String FILE_EXTENSION1 = "JAVA";
static final String FILE_EXTENSION2 = "JSP";
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("输入文件夹路径: ");
traverseFolder(in.nextLine());
}
public static void traverseFolder(String parentFolderPath) {
File parentFolder = new File(parentFolderPath);
File[] childrenFiles = null;
if (parentFolder.isFile()) {
if (isTextFile(parentFolder)) {
try {
System.out.println(
"文件路径: " + parentFolder.getAbsolutePath());
printFile(parentFolder);
System.out.println("");
} catch (IOException ioe) {
System.exit(1);
}
} else {
// System.out.println("This directory doesn't contain any
// files!!");
return;
}
} else {
childrenFiles = parentFolder.listFiles();
if (childrenFiles.length == 0) {
return;
}
if (!containsDirectory(childrenFiles)) {
for (File file : childrenFiles) {
if (isTextFile(file)) {
try {
System.out.println(
"File Location: " + file.getAbsolutePath());
printFile(file);
System.out.println("");
} catch (IOException ioe) {
System.exit(1);
}
}
}
} else {
for (File file : childrenFiles) {
traverseFolder(file.getAbsolutePath());
}
}
}
}
private static boolean containsDirectory(File[] files) {
for (File f : files) {
if (f.isDirectory()) {
return true;
}
}
return false;
}
/**
* 输出读取的内容到控制台
*
* @param file
* @throws IOException
*/
private static void printFile(File file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
while (line != null) {
// System.out.println(line);
line = reader.readLine();
writeToFile(line);
}
System.out.println("完成");
}
public static void writeToFile(String content) {
FileWriter fw = null;
try {
// 如果文件存在,则追加内容;如果文件不存在,则创建文件
File f = new File("E:\\test.txt");
fw = new FileWriter(f, true);
} catch (IOException e) {
e.printStackTrace();
}
PrintWriter pw = new PrintWriter(fw);
pw.println(content);
pw.flush();
try {
fw.flush();
pw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static boolean isTextFile(File file) {
String fileName = file.getName();
int i = fileName.lastIndexOf('.');
String fileExtension = fileName.substring(i + 1).toUpperCase();
if (i > 0 && fileExtension.equals(FILE_EXTENSION1)
|| fileExtension.equals(FILE_EXTENSION2)) {
return true;
}
return false;
}
}