4

How to set read-only access for a file that's been created and written using java InputStream API.

John Eipe
  • 10,922
  • 24
  • 72
  • 114
  • 1
    not quite clear what you're asking but you can use `java.io.File.setReadOnly()` to set a file to readonly. – wero Oct 05 '15 at 11:27

4 Answers4

5

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

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

The Law
  • 344
  • 3
  • 20
  • Thank for your answer, but my teacher said to me : " java can't intercede to operating system ", and we can intercede it through keyword " Native" in java . it mean we can use language C to write a method because language C can intercede with operation system . (ex : window,....). And i try to learn how to do it, if you have an opinion , let's describe it :) – Shmily Nguyễn Nov 01 '15 at 15:55
1

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.

Luke Melaia
  • 1,470
  • 14
  • 22
0

You could create new file object like this with readOnly property:

File readOnlyFile= new File("C:/test.txt");
readOnlyFile.setReadOnly();
Abhishek Shah
  • 1,394
  • 1
  • 16
  • 25