如何设置文件的隐藏属性

发布于 2024-11-03 12:32:18 字数 672 浏览 2 评论 0原文

我正在尝试创建一个静态方法来隐藏文件。 我找到了一些可能的方法来做到这一点,我写了这个:

public static void hide(File src) throws InterruptedException, IOException {

    if(System.getProperty("os.name").contains("Windows"))
    {
        Process p = Runtime.getRuntime().exec("attrib +h " + src.getPath());
        p.waitFor();
    }
    else
    {
        src.renameTo(new File(src.getParent()+File.separator+"."+src.getName()));
    }
}

不幸的是,这在 Windows 中不起作用,在 Ubuntu 上也不起作用...... 在Oracle的教程中我找到了这种方法

Path file = ...;

Files.setAttribute(file, "dos:hidden", true);

,但我不知道如何使用它,因为我的JDK没有“Path”类。 任何人都可以帮我提供一种可以在 unix 操作系统和 Windows 上运行的方法吗?

I'm trying to create a static method that let me hide a file.
I've found some possible way to do that and I wrote this:

public static void hide(File src) throws InterruptedException, IOException {

    if(System.getProperty("os.name").contains("Windows"))
    {
        Process p = Runtime.getRuntime().exec("attrib +h " + src.getPath());
        p.waitFor();
    }
    else
    {
        src.renameTo(new File(src.getParent()+File.separator+"."+src.getName()));
    }
}

Unfortunatley this isn't working in windows and neither on Ubuntu...
In Oracle's tuorials I've found this way

Path file = ...;

Files.setAttribute(file, "dos:hidden", true);

but I don't know how to use it because my JDK doesn't have the class "Path".
Can anyone help me with a method that can work in unix OS and Windows?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

爱已欠费 2024-11-10 12:32:19

Path 类是在 Java 7 中引入的。

在 Java 7 之前,没有内置的方法来访问这样的属性,因此您必须执行类似于您正在尝试的操作(并且在Unix-y 操作系统没有“隐藏属性”,但所有以 . 开头的文件默认情况下都是隐藏的)。

关于您的 exec() 调用,有 一篇很棒的(如果有点旧)文章列出了所有可能出错的东西以及如何修复它(不幸的是,这是一个相当复杂的过程)。

还有一个小注意事项: new File(src.getParent()+File.separator+"."+src.getName()) 可以替换为 新文件(src. getParent(), "." + src.getName()),这样会更简洁一些。

The Path class was introduced in Java 7.

Before Java 7 there was no built-in way to access properties like this, so you'll have to do something similar to what you're trying (and on Unix-y OS there is no "hidden property", but all files that start with a . are hidden by default).

Regarding your exec() call there's a great (if a bit old) article that lists all the stuff that can go wrong and how to fix it (it's quite an involved process, unfortunately).

And a minor note: new File(src.getParent()+File.separator+"."+src.getName()) can be replaced by new File(src.getParent(), "." + src.getName()), which would be a bit cleaner.

甲如呢乙后呢 2024-11-10 12:32:19

如果文件不是父文件,getParent() 将返回 null。也许您想要的 unix 是

src.renameTo(new File(src.getParent(), '.'+src.getName()));

Java 7 中提供的 Path

If a file as not parent, getParent() will return null. Perhaps what you wanted for unix was

src.renameTo(new File(src.getParent(), '.'+src.getName()));

Path is available in Java 7.

澜川若宁 2024-11-10 12:32:19

您将无法使用标准 JDK 代码来实现此目的。 File 类提供了 isHidden 方法,但是,它清楚地表明隐藏的概念取决于文件系统:

测试以此命名的文件是否
抽象路径名是一个隐藏文件。
隐藏的确切定义是
依赖于系统。在 UNIX 系统上,
文件被认为是隐藏的,如果它
名称以句点字符开头
('.')。在 Microsoft Windows 系统上,
文件被认为是隐藏的,如果
已在中标记为这样
文件系统。

因此,您需要编写特定于平台的代码(JNI?)来隐藏文件。

you won't be able to achieve this with standard JDK code. The File class offers an isHidden method, however, it states clearly that the concept of hidden is file system dependent:

Tests whether the file named by this
abstract pathname is a hidden file.
The exact definition of hidden is
system-dependent. On UNIX systems, a
file is considered to be hidden if its
name begins with a period character
('.'). On Microsoft Windows systems, a
file is considered to be hidden if it
has been marked as such in the
filesystem.

As such you need to write platform specific code (JNI?) to hide a file.

单挑你×的.吻 2024-11-10 12:32:19

操作系统检测代码:

public class OperatingSystemUtilities
{
    private static String operatingSystem = null;

    private static String getOperatingSystemName()
    {
        if (operatingSystem == null)
        {
            operatingSystem = System.getProperty("os.name");
        }

        return operatingSystem;
    }

    public static boolean isWindows()
    {
        String operatingSystemName = getOperatingSystemName();
        return operatingSystemName.startsWith("Windows");
    }

    public static boolean isMacOSX()
    {
        String operatingSystemName = getOperatingSystemName();
        return operatingSystemName.startsWith("Mac OS X");
    }

    public static boolean isUnix()
    {
        return !isWindows();
    }
}

隐藏文件代码:

public static String hideFile(String filePath) throws IOException
{
    Path path = Paths.get(filePath);

    if (OperatingSystemUtilities.isWindows())
    {
        Files.setAttribute(path, "dos:hidden", Boolean.TRUE, LinkOption.NOFOLLOW_LINKS);
        return path.toString();
    } else if (OperatingSystemUtilities.isUnix())
    {
        String filename = path.getFileName().toString();

        if (filename.startsWith("."))
        {
            return path.toString();
        }

        // Keep trying to rename
        while (true)
        {
            Path parent = path.toAbsolutePath().getParent();
            Path newPath = Paths.get(parent + File.separator + "." + filename);

            // Modify the file name when it exists
            if (Files.exists(newPath))
            {
                int lastDotIndex = filename.lastIndexOf(".");

                if (lastDotIndex == -1)
                {
                    lastDotIndex = filename.length();
                }

                Random random = new Random();
                int randomNumber = random.nextInt();
                randomNumber = Math.abs(randomNumber);
                filename = filename.substring(0, lastDotIndex) + randomNumber + filename.substring(lastDotIndex, filename.length());

                continue;
            }

            Files.move(path, newPath);

            return newPath.toString();
        }
    }

    throw new IllegalStateException("Unsupported OS!");
}

注意,在Unix上重命名隐藏文件时要注意避免文件名冲突。这就是代码所实现的,尽管它不太可能实现。

Operating system detection code:

public class OperatingSystemUtilities
{
    private static String operatingSystem = null;

    private static String getOperatingSystemName()
    {
        if (operatingSystem == null)
        {
            operatingSystem = System.getProperty("os.name");
        }

        return operatingSystem;
    }

    public static boolean isWindows()
    {
        String operatingSystemName = getOperatingSystemName();
        return operatingSystemName.startsWith("Windows");
    }

    public static boolean isMacOSX()
    {
        String operatingSystemName = getOperatingSystemName();
        return operatingSystemName.startsWith("Mac OS X");
    }

    public static boolean isUnix()
    {
        return !isWindows();
    }
}

Hiding the file code:

public static String hideFile(String filePath) throws IOException
{
    Path path = Paths.get(filePath);

    if (OperatingSystemUtilities.isWindows())
    {
        Files.setAttribute(path, "dos:hidden", Boolean.TRUE, LinkOption.NOFOLLOW_LINKS);
        return path.toString();
    } else if (OperatingSystemUtilities.isUnix())
    {
        String filename = path.getFileName().toString();

        if (filename.startsWith("."))
        {
            return path.toString();
        }

        // Keep trying to rename
        while (true)
        {
            Path parent = path.toAbsolutePath().getParent();
            Path newPath = Paths.get(parent + File.separator + "." + filename);

            // Modify the file name when it exists
            if (Files.exists(newPath))
            {
                int lastDotIndex = filename.lastIndexOf(".");

                if (lastDotIndex == -1)
                {
                    lastDotIndex = filename.length();
                }

                Random random = new Random();
                int randomNumber = random.nextInt();
                randomNumber = Math.abs(randomNumber);
                filename = filename.substring(0, lastDotIndex) + randomNumber + filename.substring(lastDotIndex, filename.length());

                continue;
            }

            Files.move(path, newPath);

            return newPath.toString();
        }
    }

    throw new IllegalStateException("Unsupported OS!");
}

Note that you have to pay attention to avoid a file name clash when renaming to hide the file on Unix. This is what the code implements despite it being unlikely.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文