2012-10-15 111 views
6

我得到的java.io.File使用方法File.listFiles()文件的列表,但它返回一些系統文件,比如(.sysetc),不包括系統文件...我需要排除所有系統相關文件的(Windows,Linux,Mac),同時返回列表。任何人都可以解決我的問題嗎?在file.lists()在Java中

+2

如何定義「系統文件」? – dmeister

+0

你不能自己過濾結果列表來排除你不想要的文件嗎? – Bernard

回答

2

我不認爲這有一個通用的解決方案。首先,操作系統(如Linux和MacOS)沒有明確的「系統文件」概念,也沒有明確的區分系統文件和非系統文件的方式。

我認爲你的打賭是決定你的系統文件是什麼意思,並編寫你自己的代碼來過濾它們。

2

通常使用文件過濾器來完成文件列表的過濾。

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. 

     } 
    }); 

問題是你如何定義系統文件。例如,如果您想過濾掉所有擴展名爲.sys的文件,這很簡單。如果不是,請定義您的標準。如果您難以執行您的標準,請提出具體問題。

2

正如其他人所指出的,有些操作系統沒有定義「系統文件」

但是,如果您使用的是Java 7,有一個叫NIO.2新的擴展,它可以幫助你在Windows下:

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

我想實現一個簡單的FileFilter用邏輯來確定,如果一個文件是否是系統文件,並以AlexR showed in his answer的方式使用它的實例。像這樣的東西(規則a僅用於演示目的!):

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