FileoutputStream FileNotFoundException

Mr.choi picture Mr.choi · Dec 31, 2015 · Viewed 9.6k times · Source

I'm using java SE eclipse. As I know, When there are no file named by parameter FileOutputStream constructor create new file named by parameter. However, with proceeding I see that FileOutputStream make exception 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".

    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

Answer

The Javatar picture The Javatar · Dec 31, 2015

It will throw a FileNotFoundException if the file doesn't exist and cannot be created (doc), but it will create it if it can. 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)

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

Answer from here: Java FileOutputStream Create File if not exists