Exception of system files in .lists () file in java

I get a list of files using the File.listFiles() method in java.io.File , but it returns some system files such as ( .sys and etc ) .. I need to exclude all system-related files (Windows, Linux, Mac ) when returning lists. Can anyone solve my problem?

+6
source share
4 answers

I would use a simple FileFilter with logic to determine if the file is a system file or not, and use an instance of it, as AlexR showed in his answer . Something like this (the rules are just for demonstration!):

 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; } 
+3
source

I do not think there is a general solution. For starters, operating systems such as Linux and MacOS do not have a clear idea of ​​a β€œsystem file” or an obvious way to distinguish a system file from a non-system file.

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

+2
source

Typically, file list filtering is performed using a file filter.

  new java.io.File("dir").listFiles(new FileFilter() { @Override public boolean accept(File pathname) { // add here logic that identifies the system files and returns false for them. } }); 

The problem is how you define system files. If, for example, you want to filter out all files with the extension .sys , it's simple. If not, please define your criteria. If you are having difficulty meeting your criteria, ask a specific question.

+2
source

As others have pointed out, some operating systems do not have a definition for a "system file."

However, if you are using Java 7, there is a new extension called NIO.2 that can help you on Windows:

 Path srcFile = Paths.get("test"); DosFileAttributes dfa = Files.readAttributes(srcFile, DosFileAttributes.class); System.out.println("isSystem? " + dfa.isSystem()); 
+2
source

Source: https://habr.com/ru/post/927756/


All Articles