how to set read only access for file using java

有些话、适合烂在心里 提交于 2020-01-06 02:19:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!