Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify a hidden file in Java

Tags:

java

file

java-io

I have a file that user downloads and then I execute a command within java to hide the file:

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?

Thanks for your ideas.

like image 713
Marquinio Avatar asked Jan 23 '23 01:01

Marquinio


2 Answers

I agree with Dolph, however you might also consider alternatives to using hidden files. The first is you are now dependent on the (Windows) "attrib" command. 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. For example in Windows a standard location to put your application data is in the folder "Application Data". You can find this folder using the System property "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:

//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 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.

like image 167
M. Jessup Avatar answered Jan 31 '23 19:01

M. Jessup


Unhide the file first:

Runtime.getRuntime().exec("attrib -H myFile.txt");
                                  ^
like image 38
Dolph Avatar answered Jan 31 '23 20:01

Dolph