使用Java在Windows上隐藏文件/文件夹
题
我需要在 Windows 和 Linux 上隐藏文件和文件夹。我知道在文件或文件夹的前面附加一个“.”会使其在 Linux 上隐藏。如何在 Windows 上隐藏文件或文件夹?
解决方案
有关的Java 6和下文中,
您将需要使用本地通话,这里是Windows的一种方式。
Runtime.getRuntime().exec("attrib +H myHiddenFile.java");
您应该学习一些关于Win32的API或Java本机。
其他提示
您想要的功能是即将发布的 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);
}
设置属性可以使用 Dos文件属性视图
考虑到这些事实,我怀疑 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文件系统异常。如果该文件的名称与一个周期开始时,那么它也将在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.
}
上的窗户,用java NIO,文件
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样品。
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 e.g. 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);
使用此代码,它可能会解决你的问题。
不隶属于 StackOverflow