从Java中的多个线程写入excel文件

时间:2015-05-29 10:54:34

标签: java multithreading excel selenium selenium-grid

我有一个读取和写入excel文件的selenium测试。读取是通过将所有数据加载到散列映射的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();
    }
}

2 个答案:

答案 0 :(得分:0)

您的代码没有显示您正在同步该方法,是否可以粘贴同步代码?

以防万一。记住 - 同步静态方法在同步静态方法所属的类的类对象上同步,这与实例同步方法不同。

答案 1 :(得分:0)

问题,很可能就在这里: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();
    }
}