FileOutputStream的FileNotFoundException

5
我正在使用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()

如果有任何奇怪的情况,请告诉我,谢谢。

请分享完整的异常信息。也许你正在一个只读目录中? - Jan
wb到底是什么?请发布完整的相关代码。 - Arnaud
不,这是一个普通的目录。你需要更多的代码吗?你对我的代码有什么问题吗? - Mr.choi
'new File("data.xlsx").createNewFile();' 这段代码能正常工作吗? - Arnaud
代码没问题 - 但异常会提供更多关于失败原因的细节。 - Jan
'new File("data.xlsx").createNewFile();' 创建新文件。 - Mr.choi
2个回答

8
如果文件不存在且无法创建(文档),则会抛出FileNotFoundException,但如果可以创建,则会创建该文件。为确保,您应先测试文件是否存在,然后再创建FileOutputStream(如果不存在,则使用createNewFile()创建)。
File yourFile = new File("score.txt");
yourFile.createNewFile();
FileOutputStream oFile = new FileOutputStream(yourFile, false); 

以下是答案:Java FileOutputStream 如果文件不存在则创建文件


这是否意味着 FileOutputStream 根据参数情况来创建新文件? - Mr.choi
2
这意味着如果文件不存在,它通常会创建文件,但如果无法创建文件(例如:没有权限),则会抛出该异常。 - The Javatar

1

还有一种情况,当文件已经存在但文件属性隐藏被设置时,在Windows上使用new FileOutputStream("...")会抛出FileNotFoundException异常。

在这种情况下,唯一的解决方法是在打开文件流之前重置隐藏属性,例如:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接