【问题标题】:FileoutputStream FileNotFoundExceptionFileoutputStream FileNotFoundException
【发布时间】:2016-04-05 05:46:06
【问题描述】:

我正在使用 java SE eclipse。 据我所知,当没有由参数 FileOutputStream 构造函数命名的文件时,创建由参数命名的新文件。但是,随着继续,我看到 FileOutputStream 产生异常 FileNotFoundException。我真的不知道为什么需要这个例外。我的知识有什么问题吗?

我的代码如下(制作工作簿并写入文件。在此代码中,虽然没有文件“data.xlsx”,但 FileOutpuStream 制作文件“data.xlsx”。

    public ExcelData() {
    try {
        fileIn = new FileInputStream("data.xlsx");
        try {
            wb = WorkbookFactory.create(fileIn);
            sheet1 = wb.getSheet(Constant.SHEET1_NAME);
            sheet2 = wb.getSheet(Constant.SHEET2_NAME);
        } catch (EncryptedDocumentException | InvalidFormatException | IOException e) {
            e.printStackTrace();
        } // if there is file, copy data into workbook
    } catch (FileNotFoundException e1) {
        initWb();
        try {
            fileOut = new FileOutputStream("data.xlsx");
            wb.write(fileOut);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 

    } // if there is not file, create init workbook

} // ExcelData()

如果有什么奇怪的,请告诉我,谢谢

【问题讨论】:

  • 请分享完整的例外情况?也许您在只读目录中?
  • wb 到底是什么?请发布完整的相关代码。
  • 不,这是一个普通目录。您需要更多代码吗?你对我的代码有什么问题吗?
  • 是否'new File("data.xlsx").createNewFile();'工作吗?
  • 代码没问题 - 但异常将提供有关失败原因的更多详细信息

标签: java apache-poi fileoutputstream


【解决方案1】:

如果文件不存在且无法创建 (doc),它将抛出 FileNotFoundException,但如果可以,它将创建它。为了确保您可能应该在创建 FileOutputStream 之前首先测试文件是否存在(如果不存在,则使用 createNewFile() 创建)

File yourFile = new File("score.txt");
yourFile.createNewFile();
FileOutputStream oFile = new FileOutputStream(yourFile, false); 

从这里回答:Java FileOutputStream Create File if not exists

【讨论】:

  • 这是否意味着每个案例取决于参数 FileOutputStream 是否创建新文件??
  • 这意味着如果文件不存在它应该正常创建文件但如果它无法创建文件(例如:没有权限)将抛出该异常跨度>
【解决方案2】:

还有另一种情况,new FileOutputStream("...") 抛出 FileNotFoundException,即在 Windows 上,当文件存在但设置了文件属性 hidden

这里没有办法,只能在打开文件流之前重置隐藏属性,比如

Files.setAttribute(yourFile.toPath(), "dos:hidden", false); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 2013-10-24
    • 2023-03-18
    • 2019-09-17
    相关资源
    最近更新 更多