Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a read-only file

I was wondering wether it is possible to create or simulate a file with a content set at creation and the assurance that nobody can ever change the file. If possible, can I do it in java?

like image 680
Samuel Avatar asked Dec 09 '22 02:12

Samuel


2 Answers

Setting a file to read only is not going to make it so no one can ever change it. It takes about 3 seconds to unset the read only flag. The file can then be opened in a hex editor or other program that can handle the file type and changes can be made.

like image 152
Kenneth Funk Avatar answered Jan 03 '23 10:01

Kenneth Funk


yes we can make read only file in java using setReadOnly() method.

After using this method, you will not be able to write or edit into the file.

import java.io.File;

public class FileReadOnly {
  public static void main(String[] args) {
    File file = new File("c:/file.txt");
    file.setReadOnly();
    System.out.println("File is in read only mode");
    }
}

or in this way also.

import java.io.File;
import java.io.IOException;

public class FileAttributesDemo {

  public static void main(String[] args) throws IOException {
    // Create a new file, by default canWrite=true, readonly=false
    File file = new File("test.txt");
    if (file.exists()) {
      file.delete();
    }
    file.createNewFile();
    System.out.println("Before. canWrite?" + file.canWrite());

    // set to read-only, atau canWrite = false */
    file.setWritable(false);
    System.out.println("After. canWrite?" + file.canWrite());
  }
}
like image 43
Java Avatar answered Jan 03 '23 12:01

Java