dom4j乱码问题 1字节的UTF-8序列的字节1无效

最好的方法:使用程序自动处理,当遇到这种异常时使用InputStreamReader读取文件

使用OutputStreamWriter 编码设置为“UTF-8”格式后写入文件。
说实在的单单调用.setEncoding(“UTF-8”),根本没有用

保存

public static void writeToXML(Document document) throws IOException {
        FileOutputStream out = new FileOutputStream(path);
        OutputStreamWriter oStreamWriter = new OutputStreamWriter(out, "UTF-8");
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter writer = new XMLWriter(oStreamWriter, format);
        writer.write(document);
        writer.close();

    }

读取

public static Document getDocument() throws Exception  {
        SAXReader saxReader = new SAXReader();
        FileInputStream fin=new FileInputStream(path);
        InputStreamReader iStreamReader= new InputStreamReader(fin, "UTF-8");
        return saxReader.read(iStreamReader,"UTF-8"); // 读取XML文件,获得document对象
    }

你可能感兴趣的:(JavaWeb)