创建Path对象数组

时间:2017-08-17 13:53:08

标签: java file file-io path

我目前正在尝试编写一个删除指定文件夹中重复文件的程序。我被告知使用Path对象支持File对象,并且Path的API具有File所拥有的所有内容,但我似乎无法弄清楚如何在其中创建一系列项目给定的路径。将Path转换为File并使用listFiles()方法是不好的做法?将路径转换为文件并返回,就像我在下面的代码中那样做是不好的做法?

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;  
}

}

0 个答案:

没有答案