我目前正在尝试编写一个程序,删除给定文件夹中的重复文件。我被告知要使用路径对象来支持文件对象,并且路径的API拥有文件中所有的东西,但是我似乎不知道如何在给定的路径中创建一个项目的数组。将路径转换为文件并使用列表文件()方法是不是很糟糕的实践?就像我在下面的代码中所做的那样,从一个路径转换为一个文件并返回到一个文件,这是不是很糟糕的实践?
public class FileIO {
final static String FILE_PATH = "C:\\Users\\" + System.getProperty("user.name") + "\\Documents\\Duplicate Test";
public static void main(String args[]) throws IOException {
Path path = Paths.get(FILE_PATH);
folderDive(path);
}
public static void folderDive(Path path) throws IOException {
File [] pathList = path.toFile().listFiles();
ArrayList<String> deletedList = new ArrayList<String>();
Arrays.sort(pathList);
BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_PATH + "\\Deleted.txt"));
deletedList.add("Listed Below are files that have been succesfully deleted: ");
for(int pivot = 0; pivot < pathList.length - 1; pivot++) {
for(int index = pivot + 1; index < pathList.length; index++) {
if(pathList[pivot].exists() && pathList[index].exists() &&
fileCompare(pathList[pivot].toPath(), pathList[index].toPath())) {
deletedList.add(pathList[index].getName());
pathList[index].delete();
}
}
}
for(String list: deletedList) {
writer.write(list);
writer.newLine();
}
writer.close();
}
public static boolean fileCompare(Path firstFile, Path comparedFile) throws IOException {
byte [] first = Files.readAllBytes(firstFile);
byte [] second = Files.readAllBytes(comparedFile);
if(Arrays.equals(first, second)) {
return true;
}
return false;
}
}
什么版本的java?
我的版本是java8
请检查 codereview.stackexchange.com 这是一个合适的地方来回答这样的问题;)