java如何使用DirectoryStream过滤隐藏文件。滤器
我正在尝试使用NIO类过滤隐藏文件
在Windows 10上运行附加代码时,我得到以下输出:
Files:
c:\Documents and Settings
c:\PerfLogs
c:\Program Files
c:\Program Files (x86)
c:\Users
c:\Windows
Paths:
c:\$Recycle.Bin
c:\Config.Msi
c:\Documents and Settings
c:\Intel
c:\IntelOptaneData
c:\OEM
c:\OneDriveTemp
c:\PerfLogs
c:\Program Files
c:\Program Files (x86)
c:\ProgramData
c:\Recovery
c:\System Volume Information
c:\Users
c:\Windows
文件下显示的列表(使用旧的File.listFiles(FileFilter)
方法)是我在Windows文件资源管理器中看到的列表,也是我希望看到的列表(文档和设置除外,我知道如何修复它)
- 为什么NIO方法不以同样的方式过滤隐藏文件李>
- 如何使NIO过滤保持不变李>
以下是测试代码:
import java.io.*;
import java.nio.file.*;
public class ListFilesNIO
{
public static void main(String[] args) throws Exception
{
String directory = "c:\\";
// Use old File I/O
FileFilter fileFilter = new FileFilter()
{
@Override
public boolean accept(File entry)
{
if (entry.isHidden()) return false;
return true;
}
};
System.out.println("Files:");
File[] files = new File( directory ).listFiles( fileFilter );
for (File file : files)
{
System.out.println( "\t" + file );
}
// Use NIO
DirectoryStream.Filter<Path> pathFilter = new DirectoryStream.Filter<Path>()
{
@Override
public boolean accept(Path entry) throws IOException
{
if (Files.isHidden( entry )) return false;
return true;
}
};
System.out.println();
System.out.println("Paths:");
DirectoryStream<Path> paths = Files.newDirectoryStream(Paths.get( directory ), pathFilter);
for (Path path : paths)
{
System.out.println( "\t" + path );
}
}
}
注意:当我在没有过滤器的情况下运行代码时,在这两种情况下都会显示18个文件。因此,第一种方法是过滤12个隐藏文件,第二种方法是只过滤3个文件
# 1 楼答案
我最终使用了:
正如我在问题中提到的,我还希望隐藏
Documents and Settings
Documents and Settings
是指向C:\Users
的链接Files.readAttributes(…)
方法的默认实现是遵循链接。所以我猜因为c:\Users
目录没有隐藏,所以Documents and Settings
也被认为没有隐藏通过使用
LinkOption.NOFOLLOW_LINKS
它被认为是隐藏的,这就是我想要的# 2 楼答案
这不是一个bug,而是一个特性(!)从jdk7开始,Windows隐藏目录就不会被检测为隐藏,请参见此bug和此one(修复jdk13)
作为解决方法,您可以执行以下操作: