请考虑以下代码:
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();
}
}
}
当然,尝试修改只读文件将给我们一个访问消除例外。但是,如代码中所示,这不适用于文件的属性,可以根据需要对其进行修改。
当然,这意味着任何人都可以轻松地将只读属性更改回false并根据需要修改文件。
那么,为什么这是允许的,有人会如何在Java中创建一个实际的只读文件呢?
慕森卡
慕妹3242003
随时随地看视频慕课网APP
相关分类