我正在进行JUnit
测试,创建一个Excel文件,然后将其与基准文件进行比较。
然而,在测试时,我的比较以查看两个文件是否相等总是返回false。所以我尝试了一个非常示例的代码来创建相同的文件,但是在不同的位置:
代码
@Test
public void testWrite() throws SQLException, IOException
{
File createdFile = folder.newFile("myfile.xlsx");
File createdFile2 = folder.newFile("myfile2.xlsx");
// Same file created but using two different file names
FormFile tester = new FormFile(createdFile, "Harvard");
tester.write();
tester = new FormFile(createdFile2, "Harvard");
tester.write();
// Always return false
assertEquals(FileUtils.contentEquals(createdFile, createdFile2), true);
}
public class FormFile
{
private File file;
private String schoolName;
public FormFile(File file, String schoolName)
{
this.file = file;
this.schoolName = schoolName;
}
workbook = POIExcelFileProcessor.createWorkbook(FormFileTest.class.getResourceAsStream(FORM_FILE_TEMPLATE_FILENAME));
// Code to modify the workbook
POIExcelFileProcessor.writeWorkbook(workbook, file);
}
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();
fileOut.close();
workbook.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
即使使用相同的参数(这里是字符串" Harvard"),两个文件都是'内容仍然不相同,我不明白为什么。
提前致谢!
答案 0 :(得分:2)
您可以创建的最简单的电子表格将具有创建的日期时间戳。您可以验证这一点:
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class SimpleSheet {
public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook();
Sheet sh1 = wb.createSheet("Sheet1");
Row r = sh1.createRow(0);
Cell c = r.createCell(0);
c.setCellValue("Test");
// Write the output to a file
String file = "simple-poi.xlsx";
FileOutputStream out = new FileOutputStream(file);
wb.write(out);
out.close();
wb.close();
System.out.println("Generated: " + file);
}
}
运行此代码,然后将文件重命名为* .zip。您将能够看到xml文件。查看docProps / core.xml,您将看到时间戳。将使用代码创建的两个文件重命名为.zip,然后查看每个存档中的同一文件。这可能是您的两个文件之间唯一不同的内容。