简体   繁体   中英

Java - Windows 7 reading files and write them to a List

Basically, what I wanna do is to read all files from a specific path of my windows machine eg "C:\\". After reading all files to an file array, I check within the for-loop if a file is a directory or not. I'm also filtering out hidden files. After that I sort each of the 2 array lists, if the current directory is not the root directory the "../" is added and everything is written to the final array lists.

But the problem is - this java program shows me more directories than there are, I think. Because the output of the windows cmd shell for "C:\\> dir" is not the same as the output of my java program.

Any ideas how to fix that?

Output of "C:\\> dir":

{ "PerfLogs", "Program Files", "Program Files(x86)", "Users", "Windows" }

Output of this java program:

{ "Documents and Settings", "Dokumente und Einstellungen", "PerfLogs", "Program Files(x86)", "Program Files", "Users", "Windows", "pagefile.sys" }

private void getFileBrowser(String dirPATH) {
    ITEM_TEMP = new ArrayList<String>();
    PATH_TEMP = new ArrayList<String>();
    ITEM_TEMP.clear();
    PATH_TEMP.clear();

    currentWorkingDirectory = dirPATH;

    File f = new File(dirPATH);
    File[] files = f.listFiles();

    for(int i=0; i < files.length; i++) {
        File file = files[i];

        if(file.isDirectory()) {
            if(!file.isHidden() & !file.getName().startsWith("$")) {
                PATH_TEMP.add(file.getPath());
                ITEM_TEMP.add(file.getName() + "/");
            }
        }
        else {
            if(!file.isHidden()) {
                PATH_TEMP.add(file.getPath());
                ITEM_TEMP.add(file.getName());
            }
        }
    }

    Collections.sort(ITEM_TEMP);
    Collections.sort(PATH_TEMP);

    ITEM.clear();
    PATH.clear();

    if(!dirPATH.equals(rootDirectory)) {
        ITEM.add("../");
        PATH.add(f.getParent());
    }

    for(int i=0; i < ITEM_TEMP.size(); i++) {
        ITEM.add(ITEM_TEMP.get(i));
    }
    for(int i=0; i < PATH_TEMP.size(); i++) {
        PATH.add(PATH_TEMP.get(i));
    }
}

It looks like your Java code is printing out every file (pagefile.sys should be hidden by default on your system). You said that you want to filter out hidden files.

The problem lies probably in this line:

 if(!file.isHidden() & !file.getName().startsWith("$"))

& is a bitwise AND operator, you should use && -logical AND operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM