简体   繁体   English

用Java修改隐藏文件

[英]Modify a hidden file in Java

I have a file that user downloads and then I execute a command within java to hide the file: 我有一个用户下载的文件,然后我在java中执行一个命令来隐藏文件:

Runtime.getRuntime().exec("attrib +H myFile.txt");

Now later I need to access that hidden file but I'm getting 现在我需要访问该隐藏文件,但我得到了

java.io.FileNotFoundException: myFile.txt (Access is denied)

This works if file is not hidden, but the file needs to be hidden so user wont modify it. 如果文件未被隐藏,则此方法有效,但文件需要隐藏,因此用户不会修改它。 So how am I supposed to modify the hidden file? 那么我该如何修改隐藏文件呢? Is there any way to do this in Java? 有没有办法在Java中这样做?

Thanks for your ideas. 谢谢你的想法。

I agree with Dolph, however you might also consider alternatives to using hidden files. 我同意Dolph,但您也可以考虑使用隐藏文件的替代方法。 The first is you are now dependent on the (Windows) "attrib" command. 首先,您现在依赖于(Windows)“attrib”命令。 Secondly, just because a file is marked as hidden does not mean the user can not see or modify it (I have my machine set to always display hidden files). 其次,仅仅因为文件被标记为隐藏并不意味着用户无法看到或修改它(我将我的机器设置为始终显示隐藏文件)。 As an alternative you might consider using standard directory locations and filenaming conventions. 作为替代方案,您可以考虑使用标准目录位置和filenaming约定。 For example in Windows a standard location to put your application data is in the folder "Application Data". 例如,在Windows中,放置应用程序数据的标准位置位于“应用程序数据”文件夹中。 You can find this folder using the System property "user.home": 您可以使用系统属性“user.home”找到此文件夹:

System.out.println(System.getProperty("user.home"));
//prints out something like C:\Documents And Settings\smithj

You can use this create your own Application Data folder: 您可以使用它创建自己的Application Data文件夹:

//For Windows
File appDataDir = new File(System.getProperty("user.home"), "Application Data\\MyWidgetData");

Similarly in *nix environments applications usually keep their data in a .xyz directory in the home directory: 类似地,在* nix环境中,应用程序通常将其数据保存在主目录中的.xyz目录中:

//*nix OSes
System.out.println(System.getProperty("user.home"));
//prints out something like /user/home/smithj
File appDataDir = new File(System.getProperty("user.home"), ".MyWidgetData");

You can look at the property os.name to determine what environment you are running on and construct a correct path based on that. 您可以查看属性os.name以确定您正在运行的环境并基于此构建正确的路径。

Unhide the file first: 首先取消隐藏文件:

Runtime.getRuntime().exec("attrib -H myFile.txt");
                                  ^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM