简体   繁体   English

文件输出流 FileNotFoundException

[英]FileoutputStream FileNotFoundException

I'm using java SE eclipse.我正在使用 java SE eclipse。 As I know, When there are no file named by parameter FileOutputStream constructor create new file named by parameter.据我所知,当没有由参数 FileOutputStream 构造函数命名的文件时,创建由参数命名的新文件。 However, with proceeding I see that FileOutputStream make exception FileNotFoundException.但是,随着继续,我看到 FileOutputStream 产生异常 FileNotFoundException。 I really don't know Why this exception needed.我真的不知道为什么需要这个例外。 Anything wrong with my knowledge?我的知识有什么问题吗?

My code is following(make WorkBook and write into file. In this code, although there are no file "data.xlsx", FileOutpuStream make file "data.xlsx".我的代码如下(制作工作簿并写入文件。在这段代码中,虽然没有文件“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()

If anything weird, please let me know, thank you如果有什么奇怪的,请告诉我,谢谢

It will throw a FileNotFoundException if the file doesn't exist and cannot be created ( doc ), but it will create it if it can.如果文件不存在且无法创建 ( doc ),它将抛出 FileNotFoundException,但如果可以,它将创建它。 To be sure you probably should first test that the file exists before you create the FileOutputStream (and create with createNewFile() if it doesn't)为确保您可能应该在创建 FileOutputStream 之前首先测试该文件是否存在(如果不存在则使用 createNewFile() 创建)

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

Answer from here: Java FileOutputStream Create File if not exists从这里回答: Java FileOutputStream 如果不存在则创建文件

There is another case, where new FileOutputStream("...") throws a FileNotFoundException , ie on Windows, when the file is existing, but file attribute hidden is set.还有另一种情况,其中new FileOutputStream("...")抛出FileNotFoundException ,即在 Windows 上,当文件存在但文件属性hidden被设置时。

Here, there is no way out, but resetting the hidden attribute before opening the file stream, like在这里,没有办法,只能在打开文件流之前重置隐藏属性,比如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM