首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FileoutputStream FileNotFoundException

FileoutputStream FileNotFoundException
EN

Stack Overflow用户
提问于 2015-12-31 16:12:19
回答 2查看 12.1K关注 0票数 4

我使用的是java SE eclipse。据我所知,当没有以参数命名的文件时,FileOutputStream构造函数会创建一个以参数命名的新文件。但是,在继续进行过程中,我看到FileOutputStream使FileNotFoundException成为异常。我真的不知道为什么需要这个异常。我的知识有什么问题吗?

我的代码如下(生成WorkBook并写入文件。在这段代码中,虽然没有文件"data.xlsx",但FileOutpuStream生成了文件"data.xlsx“。

代码语言:javascript
复制
    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()

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-12-31 16:15:26

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

代码语言:javascript
复制
File yourFile = new File("score.txt");
yourFile.createNewFile();
FileOutputStream oFile = new FileOutputStream(yourFile, false); 

这里的答案是:Java FileOutputStream Create File if not exists

票数 7
EN

Stack Overflow用户

发布于 2021-09-07 12:16:24

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

在这里,除了在打开文件流之前重置隐藏属性之外,没有别的办法,比如

代码语言:javascript
复制
Files.setAttribute(yourFile.toPath(), "dos:hidden", false); 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34543286

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档