1. 程式人生 > >Java 在給定路徑上建立檔案,所在資料夾不存在時,如何正確建立。

Java 在給定路徑上建立檔案,所在資料夾不存在時,如何正確建立。

String strPath = "E:\\a\\aa\\aaa.txt";
File file = new File(strPath);
if(!file.exists())){
	file.createNewFile();
}

這段程式碼,如果 E:\a\aa\ 資料夾不存在,會報錯。
String strPath = "E:\\a\\aa\\aaa.txt";
File file = new File(strPath);
if(!file.exists())){
	file.file.mkdirs();
}
這段程式碼,會建立資料夾 E:\\a\\aa\\aaa.txt\。
String strPath = "E:\\a\\aa\\aaa.txt";
File file = new File(strPath);
File fileParent = file.getParentFile();
if(!fileParent.exists()){
	fileParent.mkdirs();
}
file.createNewFile();
這段程式碼可以成功建立檔案。