我试图使用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中看到的列表,也是我希望看到的列表(除了文档和设置之外,我知道如何修复该列表)。
下面是测试代码:
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个文件。
发布于 2020-05-13 21:38:35
这不是一个bug,而是一个特性(!)已知自jdk7以来,Windows隐藏目录未被检测为隐藏目录,请参见此错误和此一 (修复jdk13)。
作为一种解决办法,您可以这样做:
import java.nio.file.attribute.DosFileAttributes;
...
DirectoryStream.Filter<Path> pathFilter = new DirectoryStream.Filter<Path>()
{
@Override
public boolean accept(Path entry) throws IOException
{
DosFileAttributes attr = Files.readAttributes(entry, DosFileAttributes.class);
return !attr.isHidden();
}
};发布于 2020-05-14 00:48:42
最后我用了:
DirectoryStream.Filter<Path> pathFilter = new DirectoryStream.Filter<Path>()
{
@Override
public boolean accept(Path entry) throws IOException
{
DosFileAttributes attr = Files.readAttributes(entry, DosFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
return !attr.isHidden();
}
};正如我在问题中提到的,我也希望Documents and Settings被隐藏。
Documents and Settings是指向C:\Users的链接。
Files.readAttributes(…)方法的默认实现是遵循链接。所以我想,因为c:\Users目录没有隐藏,所以Documents and Settings也被认为是不隐藏的。
通过使用LinkOption.NOFOLLOW_LINKS,它被认为是隐藏的,这正是我想要的。
https://stackoverflow.com/questions/61785056
复制相似问题