Чтобы сделать так, чтобы setWritable (true) не включало запись снова, вы можете расширить File и переопределить методы setWritable ().
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());
}
}
, который производит вывод:
Before. canWrite? true
Set Writable False. canWrite? false
Set Writable True. canWrite? false