gpt4 book ai didi

Java如何删除设置了IMMUTABLE位的文件

转载 作者:IT老高 更新时间:2023-10-28 21:06:20 24 4
gpt4 key购买 nike

在我从外部源复制文件的 Java 8 项目中工作。在其中一个源中,文件设置为不可变位标志。

OSX 中是这样设置的

sudo chflags schg /path/to/file

Linux

chattr +i /path/to/file

我现在需要删除已复制的文件。我一直在使用 Apache Commons IO 来删除目录,

FileUtils.deleteDirectory(new File("/path/here"));

但是,这会因 java.io.IOException 异常而崩溃。

是否有任何跨平台方式来删除这些文件?正在运行的进程是文件的所有者。

最佳答案

问题:因为我们知道设置了不可变属性的文件,不能被任何用户删除。即使是root用户也无法删除以下文件。

现在,为了能够删除文件,您必须删除不可变属性,然后删除文件。

现在,你要做的就是通过代码应用shell命令并移除文件的不可变属性。

正如你提到的跨平台问题

所以基本算法是


第 1 步: 检测您正在使用的操作系统
示例代码将是:

private static String OS = System.getProperty("os.name").toLowerCase();
if(OS.indexOf("win") >= 0)
//your code for windows OS.
else if(OS.indexOf("mac") >= 0)
//your code for MAC OS.
else if(OS.indexOf("sunos") >= 0)
//your code for Solaris OS

注意:我没有添加检查所有操作系统的代码。所以你自己看看吧。
第二步:这一步帮你解决跨平台问题
通过java.lang.Runtime.exec发出相应的shell命令删除文件的不可变属性。
java.lang.Runtime.exec .
java.lang.Runtime.exec :通过它,您可以为任何底层环境(无论是 MAC、Windows、Linux 等)提供适当的 shell 命令。

示例代码为

//if the OS detected is Linux then
Process p = Runtime.getRuntime().exec("chattr -i /path/to/file");
//Play with the process as you would like to, using the documentation.
//else if the OS detected is OSX then : example to unlock in OSX
Process p = Runtime.getRuntime().exec("chflags nouchg /path/to/file");
//Play with the process as you would like to, using the documentation.
//else if the OS detected is say Windows then : example to unlock in Windows
Process p = Runtime.getRuntime().exec("ATTRIB -s -h /path/to/file");
//-s -h are used to unlock and unhide (i dont the Antonym of hide :p ) the file in windows
//Play with the process as you would like to, using the documentation.

注意:要运行包含管道的其他 shell 命令,您可以使用这种示例代码:

Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});


步骤 3: 使用相同的 Runtime.exec() 来检查不可变属性是否已被移除,如下所示:

Process p = Runtime.getRuntime().exec("lsattr /whateverPath");
//Play with the process to check whether the attribute is set or not, using the documentation.


第 4 步: 如果第 3 步为真|假,无论您应用什么逻辑,然后使用 Runtime.exec() 再次使用您的相应命令删除文件。

看一下上面的 java.lang.Runtime.exec 链接文档并使用它。
请让我知道它是否在某种程度上有所帮助。

关于Java如何删除设置了IMMUTABLE位的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40882808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com