0

I should get a list of file contained in a directory.

What I do is:

    File file = new File(PATH);
    for (File index:file.listFiles)
        System.out.println(index.toString());

The matter is that doing this I get printed also files I shouldn't see, temporary, for example.

In my test directory I have to file: ciao and test, but when I run my code I see ciao, ciao~, test~, and also other stuff if I modify a file (I suppose they are buffer file).

So, how can I get only true file, as if I was browsing my fileSystem?

4

3 回答 3

4

If you want to list only files whose attributes (name included) obey a set of conditions, you need to use another version of .listFiles() which takes a FileFilter as an argument. This interface has a sole accept() method which returns true if the file can be listed.

This simple example will filter out files whose name end with a ~:

file.listFiles(new FileFilter() {
    @Override
    public boolean accept(File pathname) {
        return !pathname.getName().endsWith("~");
    }
})

If your FileFilter is more complex than the one above, consider exernalizing it to a variable (private static final if the filter will never change).

于 2013-01-10T21:16:56.850 回答
1

use

if (!index.isHidden()) {
    System.out.println(index.toString());
}

to suppress hidden files.

you further can check for

index.isDirectory()

if you dont want subdirectory to be listed.

But dont expect an method that can read your thougts what you call an real (or clean, or nice) file.

You could write yourself a filter for that, once you now what files to exclude.

See java.io.FileFilter for more.

于 2013-01-10T21:16:52.837 回答
1

Files you don't see are probably hidden, you can check that:

File file = ...;
if(file.isHidden()){...}
于 2013-01-10T21:19:18.797 回答