JDK 7:新文件("path/to/file.html")上的现有文件为空;



我使用的是JDK 7。我有一个类,它有一个使用PrintStream创建html文件的方法。同一类中的另一个方法应该使用创建的文件并对其进行处理。问题是,一旦我使用新文件("path/to/file.html"),文件长度就会减少到0。我的代码:

public class CreatePDFServiceImpl {
private final PrintStream printStream;
public CreatePDFServiceImpl() throws IOException {
    printStream = new PrintStream("/mnt/test.html", "UTF-8");
}
public void createHtmlFile() throws IncorporationException {
    try {
        StringBuilder html = new StringBuilder();
        HtmlFragments htmlFragments = new HtmlFragments();
        html.append(htmlFragments.getHtmlTop())
 .append(htmlFragments.getHeading())
 .append(htmlFragments.buildBody())
 .append(htmlFragments.buildFooter());
        printStream.print(html.toString());
    }  finally {
        if(printStream != null) {
            printStream.close();
        }
    }
}

下一个方法应该使用在"createHtmlFile()"中创建的html文件:

 public void convertHtmlToPdf() {
    PrintStream out = null;
    try {
        File file = new File("/mnt/test.html");
        /** this code added just for debug **/
        if (file.createNewFile()){
            System.out.println("File is created!");
        } else {
            System.out.println("File already exists. size: " + file.length());
        }
        /* PDF generation commented out. */
        //out = new PrintStream("/mnt/testfs.pdf", "UTF-8");
        //defaultFileWriter.writeFile(file, out, iTextRenderer);
    } catch (IOException e) {
        throw new IncorporationException("Could not save pdf file", e);
    } finally {
        if(out != null) {
            out.close();
        }
    }

我的junit集成测试课程:

@Category(IntegrationTest.class)
public class CreatePDFServiceIntegrationTest {
private static CreatePDFServiceImpl createPDFService;
@BeforeClass
public static void init() throws IOException {
    createPDFService = new CreatePDFServiceImpl();
}
@Test
public void testCreateHtmlFile() throws IncorporationException {
    createPDFService.createHtmlFile();
    File createdFile = new File("/mnt/test.html");
    System.out.println("createdFile.length() = " + createdFile.length());
    Assert.assertTrue(createdFile.length() > 1);
}
@Test
public void testCreatePDF() throws Exception {
    File fileThatShouldExist = new File("/mnt/testfs.pdf");
    createPDFService.convertHtml2Pdf();
    Assert.assertTrue(fileThatShouldExist.exists());
}
}

第一次测试通过,输出:

 "createdFile.length() = 3440".

我检查了文件系统,有文件。大小3.44kb。

第二个测试失败,CreatePDFServiceImpl:输出

"File already exists. size: 0"

在文件系统中查看,该文件现在实际上是0字节。

我被难住了。新文件("路径")应该只创建对该文件的引用,而不是清空它?

我怀疑File.createNewFile()中有错误。我还没有完全掌握你运行代码的顺序,但你知道这会将文件大小设置为零吗?

out = new PrintStream("/mnt/testfs.pdf", "UTF-8");

来自PrintStream(File file) Javadoc:

file—要用作此打印流目标的文件。如果文件存在,则它将被截断为零大小;否则将创建文件。输出将写入文件缓冲。

我认为这是罪魁祸首,但在您的代码中,这一行被注释掉了。我说得对吗?你在运行测试时评论了这句话?

最新更新