[英]Write to an excel file from multiple threads in Java
我有一个硒测试,可以读写excel文件。 读取是通过将所有数据加载到哈希图中的dataProvider实现的。 现在,我使用Grid来同时运行多个线程。 如何使用多线程完成编写? 我了解了有关同步方法的信息,但是当我将其应用于outputStream文件时,我会失败。
我的代码:
public static void createOutputFile(String inputFilePath) {
inputFilePath = "InputPath";
outputFilePath = "OutputPath";
try {
inputFile = new FileInputStream(new File(inputFilePath));
workbook = WorkbookFactory.create(inputFile);
inputFile.close();
// save input data as output
outputFile = new FileOutputStream(outputFilePath);
workbook.write(outputFile);
outputFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static synchronized void writeToFile(Integer rowNumber, Integer cellNumber, String text) {
try {
//recreate workbook
FileInputStream file = new FileInputStream(new File(outputFilePath));
workbook = WorkbookFactory.create(file);
cell = workbook.getSheetAt(0).getRow(rowNumber).getCell(cellNumber);
if(cell == null)
cell = workbook.getSheetAt(0).getRow(rowNumber).createCell(cellNumber, Cell.CELL_TYPE_BLANK);
file.close();
outputFile = new FileOutputStream(outputFilePath);
if (rowNumber != null && cellNumber != null) {
try {
cell.setCellValue(text);
} catch (Exception e) {
System.err.println("Updating the file failed " + outputFilePath);
}
}
workbook.write(outputFile);
outputFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
您的代码未显示您正在同步方法,可以粘贴已同步的代码吗?
以防万一-同步静态方法是在同步静态方法所属类的类对象上同步的,这与实例同步方法不同。
问题很可能在这里: outputFile = new FileOutputStream(outputFilePath);
。 这是因为它创建了一个指向文件开头的新流。 因此,顺序调用将覆盖先前的材料。 要解决此问题,只需使用构造函数的另一个版本: outputFile = new FileOutputStream(outputFilePath, true);
它将在末尾附加流中的字节。 不要忘记使您的方法同步:
public static synchronized void writeToFile(Integer rowNumber, Integer cellNumber, String text) {
try {
//recreate workbook
FileInputStream file = new FileInputStream(new File(outputFilePath));
workbook = WorkbookFactory.create(file);
cell = workbook.getSheetAt(0).getRow(rowNumber).getCell(cellNumber);
if(cell == null)
cell = workbook.getSheetAt(0).getRow(rowNumber).createCell(cellNumber, Cell.CELL_TYPE_BLANK);
file.close();
outputFile = new FileOutputStream(outputFilePath, true);
if (rowNumber != null && cellNumber != null) {
try {
cell.setCellValue(text);
} catch (Exception e) {
System.err.println("Updating the file failed " + outputFilePath);
}
}
workbook.write(outputFile);
outputFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.