← 從零開始學 Java
第 56 課,共 88 課 · 10 XP
建立檔案
理論與題目說明
機器翻譯,尚未經母語人士審閱。
File f = new File("log.txt");
try {
if (f.createNewFile()) // true——建立了,false——已經存在
System.out.println("created");
else
System.out.println("already exists");
} catch (IOException e) { // 沒有權限、沒有資料夾……——受檢例外
System.out.println("error: " + e.getMessage());
}
createNewFile() 以不可分割的方式建立空的檔案:就算兩個行程同時嘗試,也只有一個能建立。
父資料夾不存在時會出現 IOException(先呼叫 getParentFile().mkdirs())。
用 Files 的話:Files.createFile(path) 在檔案已經存在時會拋出 FileAlreadyExistsException。
題目。 對輸入的每個名字建立檔案,輸出 <name>: 已建立 或 <name>: 已經存在。
名字裡含有資料夾時(a/b.txt),也要建立資料夾。最後輸出建立的檔案數。