我将String类型的数据,如String  result ="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<BookList></BookList>"然后我把它写成xml文件。代码如下: FileWriter fw;
new File("d:/PolicyImport/book/book.xml").getParentFile().mkdirs();
fw = new FileWriter("d:/PolicyImport/book/book.xml");
fw.write(result);
fw.close();
然后我得到的xml用IE打开有错误。提示文本内容中发现无效字符。处理资源 'file:///d:/PolicyImport/book/book.xml‘时出错。我把xml选择另存为utf-8格式的话,用IE开就没错。我想请教的是,我在写入文件的时候如何就能把xml写成utf-8格式呢?我明明加了那段头文件啊。大家帮忙指导一下

解决方案 »

  1.   

    FileWriter无法指定编码, 采用默认的系统编码写入文件
    可以用一些可以指定编码的writer, 如:
    new OutputStreamWriter( new FileOutputStream(file), "utf-8")
      

  2.   

    读写文件最好都用inputStream, outputStream, 用reader,writer会有编码问题, 需要注意
      

  3.   

    new OutputStreamWriter( new FileOutputStream(file), "utf-8")写文件带上编码
      

  4.   

    用outputStream如何将stirng写入文件呢
      

  5.   

    String result ="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<BookList>啊斯蒂芬</BookList>";
    OutputStream os = new FileOutputStream(new File("d:/book.xml"));
    /*FileWriter fw;
    fw = new FileWriter("d:/book.xml");
    fw.write(result);
    fw.close();*/
    Writer w = new OutputStreamWriter(os,"UTF-8");
    w.write(result);
    w.close();
    os.close();