我正在做一些编写Excel文件的代码。但是,当打开在main
函数末尾创建的文件时,Open Office会显示一条错误消息,指出该文件已被未知用户锁定。我检查了,似乎我正在使用该文件关闭对文件和工作簿的所有引用。
提前感谢您的帮助!
代码
public class StandingsFile
{
private Workbook workbook;
public StandingsFile(InputStream inputStream, File outputFile)
{
this.outputFile = outputFile;
workbook = POIExcelFileProcessor.createWorkbook(inputStream);
}
public void write()
{
// Code where the sheets in the Excel file are modified
POIExcelFileProcessor.writeWorkbook(workbook, outputFile);
}
public static void main(String[] args)
{
standingsExcelFile = new StandingsFile(StandingsCreationHelper.class.getResourceAsStream(TEMPLATE_FILENAME), outputFile);
standingsExcelFile.write();
try
{
Desktop dt = Desktop.getDesktop();
dt.open(outputFile);
}
catch (Exception ex)
{
e.printStackTrace();
}
}
}
public class POIExcelFileProcessor
{
public static Workbook createWorkbook(InputStream inputStream)
{
Workbook workbook = null;
try
{
workbook = WorkbookFactory.create(inputStream);
}
catch (Exception e)
{
e.printStackTrace();
}
return workbook;
}
public static void writeWorkbook(Workbook workbook, File outputFile)
{
try
{
FileOutputStream fileOut = new FileOutputStream(outputFile);
workbook.write(fileOut);
fileOut.flush();
workbook.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
答案 0 :(得分:3)
您需要记住在使用close
方法(在finally
块中)或使用try-with-resources语句明确地使用它时关闭文件
这是一般规则,不仅仅是使用POI。