检查文件是否允许:
- file.canExecute(); – return true, file is executable; false is not.
- file.canWrite(); – return true, file is writable; false is not.
- file.canRead(); – return true, file is readable; false is not.
- file.setExecutable(boolean); – true, allow execute operations; false to disallow it.
- file.setReadable(boolean); – true, allow read operations; false to disallow it.
- file.setWritable(boolean); – true, allow write operations; false to disallow it.
- Runtime.getRuntime().exec("chmod 777 file");
- package org.hnrsc.io;
-
-
import java.io.File;
-
import java.io.IOException;
-
-
//
-
public class JavaFileIO {
-
-
public static void main(String[] args) {
-
try {
-
String filename = "test1.txt";
-
String finalfile = "";
-
String workingDir = System.getProperty("user.dir");
-
-
-
finalfile = workingDir + File.separator + filename;
-
-
System.out.println("Final filepath: " + finalfile);
-
-
File file = new File(finalfile);
-
if (file.createNewFile()) {
-
System.out.println("File is created!");
-
} else {
-
System.out.println("File already exists.");
-
}
-
if (file.exists()) {
-
System.out.println("Is Execute allow : " + file.canExecute());
-
System.out.println("Is Write allow : " + file.canWrite());
-
System.out.println("Is Read allow : " + file.canRead());
-
}
-
-
file.setExecutable(false);
-
file.setReadable(false);
-
file.setWritable(false);
-
-
System.out.println("Is Execute allow : " + file.canExecute());
-
System.out.println("Is Write allow : " + file.canWrite());
-
System.out.println("Is Read allow : " + file.canRead());
-
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
- }
本程序执行结果有点让人疑惑,为何设置以下属性为false后,只有writable变为false了?
- file.setExecutable(false);
- file.setReadable(false);
- file.setWritable(false);
- Final filepath: N:\eclipse\workspace\JavaIO\test1.txt
- File already exists.
- Is Execute allow : true
- Is Write allow : true
- Is Read allow : true
- --------------------------
- Is Execute allow : true
- Is Write allow : false
- Is Read allow : true