问题
How to set read-only access for a file that's been created and written using java InputStream API.
回答1:
In my opinion, it's good to check whether the file has been created or exists first and then set the read only flag.
File file = new File("C:/path/file.txt");
if (file.exists()) {
file.setReadOnly();
} else {
System.out.println("File does not exists.");
}
回答2:
Well their are two ways to do it.
The first would be: myFile.setReadable(false);
. This make the file unreadable by all applications. The other way would be myFile.setReadOnly();
.
Note that in order for you to read the file from your application you will need to clear the ready only flag. To clear it use myFile.setReadable(true);
.
Another thing to note would be that setting this flag only stops SOME applications from reading it, a lot of editors allow you to clear the flag. This will not prevent the user from deleting or moving the file as well.
回答3:
Try this
File file = new File("C:\\pathToYourFile\\yourFile.txt") //for example
file.setReadOnly();
or if you use just
File file = new File("C:\\pathToDirectory");
you can lock the whole folder to be read only, if the current user has permission to modify access in that folder
回答4:
You could create new file object like this with readOnly property:
File readOnlyFile= new File("C:/test.txt");
readOnlyFile.setReadOnly();
来源:https://stackoverflow.com/questions/32947389/how-to-set-read-only-access-for-file-using-java