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

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

对于Java 6及更低版本,

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

Runtime.getRuntime().exec("attrib +H myHiddenFile.java"); 

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

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

这篇文章描述了它将如何用于您所需的: 管理元数据(文件和文件存储属性) 。 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); } 

可以使用DosFileAttributeView完成设置属性

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

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

早期的Java-s不能。

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

这是我用的:

 void hide(File src) throws InterruptedException, IOException { // win32 command line variant Process p = Runtime.getRuntime().exec("attrib +h " + src.getPath()); p.waitFor(); // p.waitFor() important, so that the file really appears as hidden immediately after function exit. } 

在Windows上,使用java nio,Files

 Path path = Paths.get(..); //< input target path Files.write(path, data_byte, StandardOpenOption.CREATE_NEW); //< if file not exist, create Files.setAttribute(path, "dos:hidden", Boolean.TRUE, LinkOption.NOFOLLOW_LINKS); //< set hidden attribute 

这是一个完全可编译的Java 7代码示例,它隐藏了Windows上的任意文件。

 import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.DosFileAttributes; class A { public static void main(String[] args) throws Exception { //locate the full path to the file eg c:\a\b\Log.txt Path p = Paths.get("c:\\a\\b\\Log.txt"); //link file to DosFileAttributes DosFileAttributes dos = Files.readAttributes(p, DosFileAttributes.class); //hide the Log file Files.setAttribute(p, "dos:hidden", true); System.out.println(dos.isHidden()); } } 

检查文件是否隐藏。 右键单击有问题的文件,您将在执行法庭后看到有问题的文件是真正隐藏的。

在此处输入图像描述

 String cmd1[] = {"attrib","+h",file/folder path}; Runtime.getRuntime().exec(cmd1); 

使用此代码可能会解决您的问题