我使用的是java SE eclipse。据我所知,当没有以参数命名的文件时,FileOutputStream构造函数会创建一个以参数命名的新文件。但是,在继续进行过程中,我看到FileOutputStream使FileNotFoundException成为异常。我真的不知道为什么需要这个异常。我的知识有什么问题吗?
我的代码如下(生成WorkBook并写入文件。在这段代码中,虽然没有文件"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()如果有什么奇怪的事,请告诉我,谢谢
发布于 2015-12-31 16:15:26
如果文件不存在且无法创建(doc),它将抛出FileNotFoundException,但如果可以,它将创建该文件。为了确保文件存在,您可能应该在创建FileOutputStream之前首先测试文件是否存在(如果不存在,则使用createNewFile()进行创建)
File yourFile = new File("score.txt");
yourFile.createNewFile();
FileOutputStream oFile = new FileOutputStream(yourFile, false); 发布于 2021-09-07 12:16:24
还有另一种情况,当文件存在但设置了文件属性hidden时,new FileOutputStream("...")会抛出FileNotFoundException。
在这里,除了在打开文件流之前重置隐藏属性之外,没有别的办法,比如
Files.setAttribute(yourFile.toPath(), "dos:hidden", false); https://stackoverflow.com/questions/34543286
复制相似问题