FileOutputStream 抛出 FileNotFoundException

Har*_*wat -2 java spring file java-io

我正在尝试与目录一起创建一个新文件,但是当我调用“fos = new FileOutputStream(file);”时 它总是抛出找不到文件的错误。这是代码

FileOutputStream fos = null;
String getName = "User";
String filePath="D:/New file";
File file;
Date date = new Date();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
String headerDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(date);

try {
  WritableWorkbook w = Workbook.createWorkbook(outputStream);
  WritableSheet s = w.createSheet("Report generate", 0);
  s.addCell(new Label(0, 0, "New File" + getName));
  s.addCell(new Label(0, 2, "Response Date: " + headerDate));
  w.write();
  w.close();

  String resultFileName = "NewFileToGenerate" +getName+headerDate+ ".xls";
  String fileName = filePath.concat(resultFileName);
  file = new File(fileName);
  file.mkdirs();
  file.createNewFile();
  fos = new FileOutputStream(file);

  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  baos = outputStream;
  // Put data in your baos
  baos.writeTo(fos);

} catch (Exception e) {

} finally {
  outputStream.close();
  fos.close();
}
Run Code Online (Sandbox Code Playgroud)

在这里,我有文件路径,但在该文件路径中,我必须通过在其中附加日期来创建另一个文件夹,然后我必须保存文件。

这是堆栈跟踪

D:/New file/NewFileToGenerateUser26/2018 20:00:14.xls(是目录)

Bro*_*rth 5

当你使用

file.makeDirs();
Run Code Online (Sandbox Code Playgroud)

它创建了所有不存在的目录,包括"NewFileToGenerate" +getName+headerDate+ ".xls". 是的,您要创建的文件是作为目录创建的。

然后你调用了 file.createNewFile(),它会返回 false,因为存在与文件同名的目录。

尝试对目录使用 FileOutputStream 将不起作用,将引发异常。

因此,您将看到此错误消息:D:/New file/NewFileToGenerateUser26/2018 20:00:14.xls (Is a directory)

可能的修复:

先创建父目录,然后在不同的语句中创建父目录后创建您要创建的文件。如:

File file = new File("parent1/parent2");
file.mkDirs();

File desiredFile = new File("parent1/parent2/desiredfile.extensionhere");
desiredFile.createNewFile();
Run Code Online (Sandbox Code Playgroud)

  • 应该是……再查一下 (2认同)
  • @HarshKumrawat 使用 `"MM_dd_yyyy-HH_mm_ss"` 作为格式。 (2认同)