gpt4 book ai didi

java - 文件已锁定以供编辑

转载 作者:行者123 更新时间:2023-11-29 08:39:54 25 4
gpt4 key购买 nike

我正在编写一些编写 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();
}
}

最佳答案

您需要记住在完成后关闭文件,可以显式地使用 close 方法(在 finally block 中)或使用 try- with-resources声明。

这是一般规则,而不仅仅是使用 POI。

关于java - 文件已锁定以供编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41078300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com