Consider the following code:
import java.io.IOException;
import java.nio.file.attribute.DosFileAttributeView;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
public class Word {
public static void main(String[] args){
try{
Path path = Paths.get("readonly.txt");
Files.createFile(path);
DosFileAttributeView dos = Files.getFileAttributeView(path,DosFileAttributeView.class);
dos.setReadOnly(true);
//Files.delete(path); Access denied exception
dos.setHidden(true); //can change attributes all we want
dos.setTimes(null,FileTime.from(Instant.now()),null);
dos.setReadOnly(false);
Files.delete(path);
}
catch(IOException e){
e.printStackTrace();
}
}
}
Naturally , trying to modify the read-only file will give us an AccessDeniedException. However, as shown in the code , that doesn't apply for the attributes of the file, which can be modified all we want.
Of course that means that anyone can easily just change the read-only attribute back to false and modify the file all they want.
So, how come this is allowed, and how would someone create an actual read-only file in Java?