我正在創建一個簡單的程序,它會嘗試從磁盤讀入「conf/conf.xml」,但是如果這個文件或dir不存在,它們將會創建它們。使用Java nio創建一個子目錄和文件
我可以做到這一點使用下面的代碼:
// create subdirectory path
Path confDir = Paths.get("./conf");
// create file-in-subdirectory path
Path confFile = Paths.get("./conf/conf.xml");
// if the sub-directory doesn't exist then create it
if (Files.notExists(confDir)) {
try { Files.createDirectory(confDir); }
catch (Exception e) { e.printStackTrace(); }
}
// if the file doesn't exist then create it
if (Files.notExists(confFile)) {
try { Files.createFile(confFile); }
catch (Exception e) { e.printStackTrace(); }
}
我的問題是,如果這樣做這真的是最優雅的方式?看起來很費神,需要創建兩個路徑才能在新的子目錄中創建一個新文件。
'Path'有'.resolve()'和'.getParent( )',所以你可以從那裏開始 – fge
我沒有得到你的異常邏輯:爲什麼你嘗試創建文件,如果該目錄不存在並且不能創建? – steffen