首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java文件屬性操作完全指南:隱藏、只讀與跨平台處理

     編輯:Java 相關知識

Java早期版本(JDK 1.6前)對文件屬性操作支持有限,僅提供File.setReadOnly()等基礎方法。對於隱藏屬性、系統屬性等進階操作,需借助平台原生命令或升級至NIO.2 API。

傳統方案:Runtime.exec調用系統命令

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");

現代方案:NIO.2 Files API (JDK 7+)

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/chflags
  • 權限問題:修改系統文件屬性需管理員權限
  • 資源管理:優先使用try-with-resources自動關閉流
  • 編碼指定:讀寫文本文件顯式指定Charset避免亂碼

JDK 7引入的java.nio.file.attribute包提供統一的跨平台屬性訪問接口,建議新項目優先採用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved