FileOutputStream 抛出 FileNotFoundException

我正在尝试与目录一起创建一个新文件,但是当我调用“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();

}

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


这是堆栈跟踪


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


慕码人2483693
浏览 378回答 3
3回答

蓝山帝景

当你使用file.makeDirs();它创建了所有不存在的目录,包括"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();

海绵宝宝撒

正如 BrokenEarth 所说,您已经使用要创建的文件的名称创建了一个目录。所以你应该分两步进行:创建目标目录在目录中创建文件要做这样的事情,你可以做这样的事情: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);        // ...    }}

RISEBY

您的文件正在创建为目录我已修复您的代码并添加了注释    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();        }    }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java