File file = new File("D:\\ddd.ddd");
file.delete();
file.createNewFile();
String cmd = "attrib +H \"" + file.getAbsolutePath() + "\"";
Runtime.getRuntime().exec(cmd);
缺點:平台鎖定 (僅 Windows)、啟動進程開銷大、無回傳碼檢查、路徑含特殊字元易出錯。
Path path = Paths.get("D:\\ddd.ddd");
Files.createFile(path); // 或 Files.write(...)
Files.setAttribute(path, "dos:hidden", true); // Windows 隱藏屬性
// Linux/Mac 無「隱藏」屬性,慣例以 "." 開頭檔名視為隱藏
// 跨平台建議:統一用 ".prefix" 命名或維護獨立索引表
| 需求 | Java 6- | Java 7+ (NIO.2) |
|---|---|---|
| 設為隱藏 (Windows) | Runtime.exec("attrib +H") | Files.setAttribute(path, "dos:hidden", true) |
| 判斷是否隱藏 | 無標準 API | Files.getAttribute(path, "dos:hidden") |
| 唯讀/系統/封存屬性 | 同上 | dos:readonly, dos:system, dos:archive |
ProcessBuilder 替代 Runtime.exec,妥善處理路徑轉義與錯誤流讀取。. 開頭檔名統一語義,避免依賴 FS 屬性。