Java早期版本(JDK 1.6前)對文件屬性操作支持有限,僅提供File.setReadOnly()等基礎方法。對於隱藏屬性、系統屬性等進階操作,需借助平台原生命令或升級至NIO.2 API。
Windows下使用attrib命令修改屬性,注意路徑含空格時需加引號:
File file = new File("D:/test file/demo.txt");
String path = "\"" + file.getAbsolutePath() + "\"";
// 設置只讀
Runtime.getRuntime().exec("attrib " + path + " +R");
// 取消只讀
Runtime.getRuntime().exec("attrib " + path + " -R");
// 設置隱藏
Runtime.getRuntime().exec("attrib " + path + +H");
// 取消隱藏
Runtime.getRuntime().exec("attrib " + path + " -H");
Path path = Paths.get("D:/test file/demo.txt");
// 讀取屬性
DosFileAttributes attrs = Files.readAttributes(path, DosFileAttributes.class);
System.out.println("隱藏: " + attrs.isHidden());
System.out.println("只讀: " + attrs.isReadOnly());
// 修改屬性
Files.setAttribute(path, "dos:hidden", true);
Files.setAttribute(path, "dos:readonly", false);
public class FileControl {
public static void main(String[] args) {
Path file = Paths.get("E:/exercise.java");
// 1. 寫入(緩衝+自動換行)
try (BufferedWriter bw = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
bw.write("大家好!");
bw.newLine();
bw.write("歡迎學習Java文件操作");
}
// 2. 追加內容
try (RandomAccessFile rf = new RandomAccessFile(file.toFile(), "rw")) {
rf.seek(rf.length());
rf.writeBytes("\n追加內容: " + System.currentTimeMillis());
}
// 3. 讀取(緩衝逐行)
try (BufferedReader br = Files.newBufferedReader(file)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
}
attrib僅限Windows,Linux/Mac需用chmod/chflagsJDK 7引入的java.nio.file.attribute包提供統一的跨平台屬性訪問接口,建議新項目優先採用。