3 回答

TA貢獻(xiàn)1843條經(jīng)驗(yàn) 獲得超7個(gè)贊
當(dāng)你使用
file.makeDirs();
它創(chuàng)建了所有不存在的目錄,包括"NewFileToGenerate" +getName+headerDate+ ".xls". 是的,您要?jiǎng)?chuàng)建的文件是作為目錄創(chuàng)建的。
然后你調(diào)用了 file.createNewFile(),它會(huì)返回 false,因?yàn)榇嬖谂c文件同名的目錄。
嘗試對(duì)目錄使用 FileOutputStream 將不起作用,將引發(fā)異常。
因此,您將看到此錯(cuò)誤消息:D:/New file/NewFileToGenerateUser26/2018 20:00:14.xls (Is a directory)
可能的修復(fù):
先創(chuàng)建父目錄,然后在不同的語(yǔ)句中創(chuàng)建父目錄后創(chuàng)建您要?jiǎng)?chuàng)建的文件。如:
File file = new File("parent1/parent2");
file.mkDirs();
File desiredFile = new File("parent1/parent2/desiredfile.extensionhere");
desiredFile.createNewFile();

TA貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊
正如 BrokenEarth 所說(shuō),您已經(jīng)使用要?jiǎng)?chuàng)建的文件的名稱創(chuàng)建了一個(gè)目錄。所以你應(yīng)該分兩步進(jìn)行:
創(chuàng)建目標(biāo)目錄
在目錄中創(chuàng)建文件
要做這樣的事情,你可以做這樣的事情:
String filePath = "D:" + File.separator + "someDir";
File dir = new File(filePath);
if (dir.exists() || dir.mkdirs()) {
// assuming that resultFileName contains the absolute file name, including the directory in which it should go
File destFile = new File(resultFileName);
if (destFile.exists() || destFile.createNewFile()) {
FileOutputStream fos = new FileOutputStream(destFile);
// ...
}
}

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超5個(gè)贊
您的文件正在創(chuàng)建為目錄我已修復(fù)您的代碼并添加了注釋
File root = new File(filePath);
//Check if root exists if not create it
if(!root.exists()) root.mkdirs();
String resultFileName = "NewFileToGenerate" +getName+headerDate+ ".xls";
File xlsFile = new File(root, resultFileName);
//check if xls File exists if not create it
if(!xlsFile.exists()) {
try {
xlsFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
添加回答
舉報(bào)