package com.robert;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class Main3 {
public static void main(String args[]) {
File file = new File("/Users/robert/Downloads/资料/");
try {
StringBuffer stringBuffer = new StringBuffer();
printFilePath(file, stringBuffer);
File logFile = new File("/Users/robert/Documents/log.txt");
logFile.delete();
FileWriter fileWriter = new FileWriter(logFile, true);
fileWriter.write(stringBuffer.toString());
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void printFilePath(File file, StringBuffer stringBuffer) throws IOException {
if (!file.exists()) {
throw new RuntimeException("file is not exist");
}
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File tempFile : files) {
printFilePath(tempFile, stringBuffer);
}
} else {
stringBuffer.append(file.getAbsolutePath()).append("\n");
}
}
public static void printFilePath2(File file) throws IOException {
if (!file.exists()) {
throw new RuntimeException("file is not exist");
}
File logFile = new File("/Users/robert/Documents/log2.txt");
logFile.delete();
FileWriter fileWriter = new FileWriter(logFile, true);
List<File> files = new LinkedList<>();
if (file.isDirectory()) {
Collections.addAll(files, file.listFiles());
} else {
// System.out.println(file.getAbsolutePath());
fileWriter.write(file.getAbsolutePath());
}
while (files.size() > 0) {
File tempFile = files.get(0);
files.remove(tempFile);
if (tempFile.isDirectory()) {
Collections.addAll(files, tempFile.listFiles());
} else {
// System.out.println(tempFile.getAbsolutePath());
fileWriter.write(tempFile.getAbsolutePath());
fileWriter.write("\n");
}
}
fileWriter.close();
}
}