String in Java to HTML file 为什么会出现额外的字符?

Why additional characters appear when String in Java to HTML file?

我已经查看了 "similar" 个问题,但无法得到我的答案。如果已经存在,请指点我。

问题:当将 String/StringBuilder 保存为 HTML 格式时,它会在页面开头添加额外的字符,我不明白为什么。示例:

’tX<!DOCTYPE html>
<html>

方法:

public void saveToHTML(){
    String fileName = "";
    if (docName != null){
        fileName += docName;
    } else {
        fileName += stdFileName;
    }
    fileName += "HTML.html";
    String tempText = new String("<!DOCTYPE html>\n<html>\n\t<body>");
    int tabCount = 3;                                                                                       
    for (int oneSec = 0; oneSec < allSections.size(); oneSec++){
        for (int onePar = 0; onePar < allSections.get(oneSec).getCountParagraphs(); onePar++){
            tempText += (convertParToHTML(allSections.get(oneSec).getParagraph(onePar), 
                                             tabCount));        
        }
    }
    tempText += ("\n\t</body>\n</html>");
    serializeDoc(fileName, tempText.toString());
}

serializeDoc() 下面:

/**
 * Helper method to serialize files
 * 
 * @param fileName name of the file to be saved with
 * @param object object to be saved in the file
 * @throws IOException 
 */
private void serializeDoc(String fileName, Object object){
    try {
        FileOutputStream file = new FileOutputStream(fileName);
        ObjectOutputStream out = new ObjectOutputStream(file);
        out.writeObject(object);
        out.close();
    } catch (IOException e){
      System.out.println("The file couldn't be created");
    }
}

您还没有发布 serializeDoc 所以我们真的不能说。但我要告诉你的是:你真的需要用文本文件跟踪你的字符集。以 ascii、latin-1、utf-8、utf-16 等格式输出相同的文本会给您不同的文件大小和不同的结果。确保一致性的最佳方法是使用 FileWriters 和 FileReaders,您可以在其中声明字符集类型

-- 更新--

咳咳咳咳!您不想在这里使用对象序列化。这会将您的 java 对象直接保存到文件中,使文件更难阅读和手动调整。将字节写入 FileOutputStream 会更好,但正如我所说,最好的解决方案是 FileWriter,这样您就可以指定要保存的字符集。