data.xml - 流的输出编码(UTF-8)不匹配声明(Cp1252)

时间:2014-08-25 02:49:12

标签: xml clojure

我尝试使用clojure/data.xml

将一些XML写入文件

我创建了一个leiningen项目(src here)。主要功能如下:

(defn -main
[]
(let [tags (element :foo {:foo-attr "foo value"}
                  (element :bar {:bar-attr "bar value"}
                           (element :baz {} "The baz value")))]
(with-open [out-file (java.io.FileWriter. "C:/Users/amyers/Desktop/output.xml")]
  (emit tags out-file))))

当我运行它时(在Windows 7 Pro,64位上),我得到以下输出:

C:\Users\amyers\projects\clojure-projects\data-xml>lein run
Exception in thread "main" java.lang.Exception: Output encoding of 
stream (UTF-8) doesn't match declaration (Cp1252)

我猜测底层的Java输出流将Cp1252作为字符编码,但是它试图编写UTF-8(这就是我想要的)。如何在UTF-8中成功编写XML?

1 个答案:

答案 0 :(得分:2)

Java.io.FileWriter似乎使用系统的默认编码,即Cp1252。您应该使用java.io.FileWriter,而不是直接使用clojure.java.io/writer,而是指定:encoding选项。

...
(with-open [w (clojure.java.io/writer "out.xml" :encoding "UTF-16")]
  (emit tags w))

如果您应该传递Writer个实例,请尝试在OutputStreamWriter上构建FileOutputStream

...
(with-open [w (java.io.OutputStreamWriter. (java.io.FileOutputStream. "out.xml") "UTF-8")] 
  (emit tags w))