使用Java在Windows上隐藏文件/文件夹

Kry*_*ten 23 java directory hidden file

我需要在Windows和Linux上隐藏文件和文件夹.我知道附加一个'.' 到文件或文件夹的前面会使它隐藏在Linux上.如何在Windows上隐藏文件或文件夹?

And*_*rew 22

对于Java 6及更低版本,

您将需要使用本机调用,这是Windows的一种方式

Runtime.getRuntime().exec("attrib +H myHiddenFile.java");
Run Code Online (Sandbox Code Playgroud)

您应该了解一下win32-api或Java Native.

  • "native"表示您正在运行特定于平台的代码.`exec()`启动DOS/Windows shell来执行DOS/Windows程序. (4认同)

Mar*_*ian 22

您希望的功能是即将推出的Java 7中NIO.2的一项功能.

这篇文章描述了它将如何用于您所需的:管理元数据(文件和文件存储属性).DOS文件属性有一个例子:

Path file = ...;
try {
    DosFileAttributes attr = Attributes.readDosFileAttributes(file);
    System.out.println("isReadOnly is " + attr.isReadOnly());
    System.out.println("isHidden is " + attr.isHidden());
    System.out.println("isArchive is " + attr.isArchive());
    System.out.println("isSystem is " + attr.isSystem());
} catch (IOException x) {
    System.err.println("DOS file attributes not supported:" + x);
}
Run Code Online (Sandbox Code Playgroud)

可以使用DosFileAttributeView完成设置属性

考虑到这些事实,我怀疑在Java 6或Java 5中有一种标准和优雅的方法来实现它.


Ste*_*son 15

Java 7可以这样隐藏DOS文件:

Path path = ...;
Boolean hidden = path.getAttribute("dos:hidden", LinkOption.NOFOLLOW_LINKS);
if (hidden != null && !hidden) {
    path.setAttribute("dos:hidden", Boolean.TRUE, LinkOption.NOFOLLOW_LINKS);
}
Run Code Online (Sandbox Code Playgroud)

早期的Java-s不能.

上面的代码不会在非DOS文件系统上引发异常.如果文件名以句点开头,那么它也将在UNIX文件系统上隐藏.

  • 您可以使用`Files.setAttribute`来接受`Path`来设置属性. (7认同)
  • 安东尼奥,在我使用的Java 7草案版中一定是这样的.我看到类似的功能现在在java.nio.file.Files中. (2认同)