如何用 out.close() 关闭 XSSF 文件?

How to close XSSF file with out.close()?

我正在尝试保存并关闭我已经成功打开但由于某种原因无法保存和关闭的现有工作簿:

//declarations etc here...

try {
            InputStream ExcelFileToRead = new FileInputStream(file);
            XSSFWorkbook  wb = new XSSFWorkbook(ExcelFileToRead);


            //XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(new File(file)));
            XSSFSheet sheet = wb.getSheetAt(0);
            XSSFRow row;
            XSSFCell cell;
            int rows; 
            rows = sheet.getPhysicalNumberOfRows();
            int cols = 1; 
            XSSFRichTextString path;
            String stpath;


            try {
            if(!Desktop.isDesktopSupported()){
                    System.out.println("Error: Desktop is not supported");
            }
            Desktop desktop = Desktop.getDesktop();
            if(filee.exists()) desktop.open(filee);
            FileOutputStream out = new FileOutputStream(file);  
            wb.write(out);
            out.close();

//code continues...

wb.write(out)打开文件成功。我已经阅读了大量的 posts/articles/docs 文章,全部使用 close() 方法来关闭 XSSF Excel 文件,但它在这里不起作用。

我该如何解决这个问题?

您不能以这种方式覆盖输入文档,正如 POIXMLDocument#write(OutputStream o) 的 Javadoc 中明确记录的那样,它被 XSSFWorkBook 继承:

Note - if the Document was opened from a File rather than an InputStream, you must write out to a different file, overwriting via an OutputStream isn't possible