Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excluding system files in file.lists() in java

Tags:

java

file-io

I am getting list of file using method File.listFiles() in java.io.File, but it returns some system files like (.sys and etc).. I am in need of excluding all system related files (Windows, Linux, Mac) while returning lists. Can any one solve my issue?

like image 213
vignesh kumar rathakumar Avatar asked Oct 15 '12 14:10

vignesh kumar rathakumar


People also ask

What does the files list () method in Java do?

list() returns the array of files and directories in the directory defined by this abstract path name. The method returns null, if the abstract pathname does not denote a directory.

How do you get the names of all files in a folder in Java?

The List() method. This method returns a String array which contains the names of all the files and directories in the path represented by the current (File) object. Using this method, you can just print the names of the files and directories.

What are hidden files Java?

The method java. io. File. isHidden() is used to check whether the given file specified by the abstract path name is a hidden file in Java. This method returns true if the file specified by the abstract path name is hidden and false otherwise.


2 Answers

I'd implement a simple FileFilter with the logic to determine, if a file is a system file or not and use an instance of it the way AlexR showed in his answer. Something like this (the rules a for demonstration purposes only!):

public class IgnoreSystemFileFilter implements FileFilter {

   Set<String> systemFileNames = new HashSet<String>(Arrays.asList("sys", "etc"));

   @Override
   public boolean accept(File aFile) {

     // in my scenario: each hidden file starting with a dot is a "system file"
     if (aFile.getName().startsWith(".") && aFile.isHidden()) {
       return false;
     }

     // exclude known system files
     if (systemFileNames.contains(aFile.getName()) {
       return false;
     }

     // more rules / other rules

     // no rule matched, so this is not a system file
     return true;
 }
like image 115
Andreas Dolk Avatar answered Oct 10 '22 07:10

Andreas Dolk


I don't think there is a general solution to this. For a start, operating systems such as Linux and MacOS don't have a clear notion of a "system file" or any obvious way to distinguish a system file from a non-system file.

I think your bet is to decide what you mean by a system file, and write your own code to filter them out.

like image 45
Stephen C Avatar answered Oct 10 '22 07:10

Stephen C