普通創建文件代碼:
String strPath = "E:\\test\\test1\\test.txt";
File file = new File(strPath);
if(!file.exists())){
file.createNewFile();
上述這段代碼,當E:\test\test1目錄不存在時,createNewFile()執行會報錯:java.io.IOException:Parent directory of file does not exist
String strPath = "E:\\test\\test1\\test.txt";
File file = new File(strPath);
if(!file.exists())){
file.mkdirs();
}
可以這麼處理:
這段代碼會創建目錄:E:\test\test1\test.txt\ 。
String strPath = "E:\\test\\test1\\test.txt";
File file = new File(strPath);
File fileParent = file.getParentFile();
if(!fileParent.exists()){
fileParent.mkdirs();//判斷父路徑是否存在,不存在,先創建父路徑
}
file.createNewFile();
上述這段代碼可以成功創建文件。原因:先判斷文件所處目錄是否存在,如果不存在則遞歸創建目錄;注意是mkdirs()而不是mkdir()。
mkdir:只能用來創建文件夾,且只能創建一級目錄,如果上級不存在,就會創建失敗。
mkdirs:只能用來創建文件夾,且能創建多級目錄 ,如果上級不存在,就會自動創建。(創建文件夾多用此)
createNewFile:只能用來創建文件,且只能在已存在的目錄下創建文件,否則會創建失敗。
FileOutputStream os=new FileOutputStream(file)也可創建文件,看情況使用