Create a read-only file

前端 未结 7 1975
我寻月下人不归
我寻月下人不归 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:17

    To make it so setWritable(true) does not enable writing again you could extend File and override the setWritable() methods.

    import java.io.File;
    import java.io.IOException;
    import java.lang.Override;
    
    public class FileAttributeDemo2 {
        private static class ReadOnlyFile extends File {
            public ReadOnlyFile(String pathname) {
                super(pathname);
            }
    
            @Override
            public boolean setWritable(boolean writeable) {
                return setWritable(writeable, true);
            }
    
            @Override
            public boolean setWritable(boolean writeable, boolean ownerOnly) {
                if (!writeable) {
                    return super.setWritable(false, ownerOnly);
                }
                return false;
            }
        }
    
        public static void main (String[] args) throws IOException {
            File file = new ReadOnlyFile("test.txt");
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            System.out.println("Before. canWrite? " + file.canWrite());
    
            file.setWritable(false);
            System.out.println("Set writable false. canWrite? " + file.canWrite());
    
            file.setWritable(true);
            System.out.println("Set writable true. canWrite? " + file.canWrite());
    
        }
    }
    

    which produces the output:

    Before. canWrite? true 
    Set Writable False. canWrite? false 
    Set Writable True. canWrite? false
    
    0 讨论(0)
提交回复
热议问题