28

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

4

7 回答 7

24

您想要的功能是即将到来的 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);
}

可以使用DosFileAttributeView设置属性

考虑到这些事实,我怀疑在 Java 6 或 Java 5 中是否存在一种标准且优雅的方式来实现这一点。

于 2009-08-18T19:15:30.887 回答
23

对于 Java 6 及以下版本,

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

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

您应该了解一些有关 win32-api 或 Java Native 的知识。

于 2009-08-18T16:29:58.210 回答
17

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

Path path = Paths.get("...");
Files.setAttribute(path, "dos:hidden", Boolean.TRUE, LinkOption.NOFOLLOW_LINKS);

早期的 Java 版本没有API这个。

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

于 2010-06-12T16:04:23.667 回答
3

这就是我使用的:

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.
}
于 2009-08-19T07:14:10.877 回答
3

在 Windows 上,使用 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
于 2016-04-07T01:45:21.623 回答
2

这是一个完全可编译的 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 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());

    }
 } 

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

在此处输入图像描述

于 2017-03-15T16:55:00.563 回答
0
String cmd1[] = {"attrib","+h",file/folder path};
Runtime.getRuntime().exec(cmd1);

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

于 2013-05-15T21:03:28.367 回答