Java 文件已锁定以进行编辑
我正在做一些编写Excel文件的代码。但是,打开在Java 文件已锁定以进行编辑,java,apache-poi,Java,Apache Poi,我正在做一些编写Excel文件的代码。但是,打开在main功能结束时创建的文件时,Open Office会显示一条错误消息,表明该文件已被未知用户锁定。我检查了一下,似乎我正在关闭对该文件和使用该文件的工作簿的所有引用 提前感谢您的帮助 代码 public class StandingsFile { private Workbook workbook; public StandingsFile(InputStream inputStream, File outputFile)
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
块中)显式关闭,也可以使用try with resources语句关闭
这是一条一般规则,不仅仅是用于使用POI。您需要记住在使用完文件后关闭它,可以使用
close
方法(在finally
块中)显式关闭,也可以使用try with resources语句
这是一条一般规则,而不仅仅是使用POI。在哪里关闭输出流?添加了fileOut.close();现在它似乎可以工作了:)。我不知道它会锁定文件。您可以将其添加为答案:)。在哪里关闭输出流?添加了fileOut.close();现在它似乎可以工作了:)。我不知道它会锁定文件。您可以将其添加为答案:)。