Create a read-only file

前端 未结 7 2040
我寻月下人不归
我寻月下人不归 2021-01-14 01:24

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

7条回答
  •  渐次进展
    2021-01-14 02:15

    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());
      }
    }
    

提交回复
热议问题