我有以下代碼:XStream的處理非英文字符
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package helloworld;
import com.thoughtworks.xstream.XStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.JOptionPane;
/**
*
* @author yccheok
*/
public class Test {
@SuppressWarnings("unchecked")
public static <A> A fromXML(Class c, File file) {
XStream xStream = new XStream();
InputStream inputStream = null;
try {
inputStream = new java.io.FileInputStream(file);
Object object = xStream.fromXML(inputStream);
if (c.isInstance(object)) {
return (A)object;
}
}
catch (Exception exp) {
exp.printStackTrace();
}
finally {
if (inputStream != null) {
try {
inputStream.close();
inputStream = null;
}
catch (java.io.IOException exp) {
exp.printStackTrace();
return null;
}
}
}
return null;
}
@SuppressWarnings("unchecked")
public static <A> A fromXML(Class c, String filePath) {
return (A)fromXML(c, new File(filePath));
}
public static boolean toXML(Object object, File file) {
XStream xStream = new XStream();
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
xStream.toXML(object, outputStream);
}
catch (Exception exp) {
exp.printStackTrace();
return false;
}
finally {
if (outputStream != null) {
try {
outputStream.close();
outputStream = null;
}
catch (java.io.IOException exp) {
exp.printStackTrace();
return false;
}
}
}
return true;
}
public static boolean toXML(Object object, String filePath) {
return toXML(object, new File(filePath));
}
public static void main(String args[]) {
String s = "\u6210\u4EA4\u91CF";
// print ???
System.out.println(s);
// fine! show 成交量
JOptionPane.showMessageDialog(null, s);
toXML(s, "C:\\A.XML");
String o = fromXML(String.class, "C:\\A.XML");
// show ???
JOptionPane.showMessageDialog(null, o);
}
}
我通過運行命令提示符下面的代碼在Windows Vista中。
1)我可以知道爲什麼System.out.println無法在控制檯中打印出中文字符嗎?
2)我打開了xstream文件。保存的值爲
<string>???</string>
如何讓xstream正確保存中文字符?
謝謝。
爲什麼我不應該使用「UTF-16」編碼? Java String是否將數據存儲在UTF-16中? – 2010-06-15 18:33:38
你可以使用UTF-16。而對於中文文本,UTF-16文件應該小於UTF-8文件。然而,如果你走這條路線,你需要在文件開始時發出一個BOM,並且我不相信'OutputStreamWriter'會自動執行。有關編碼的更多信息,請參見http://www.xml.com/axml/testaxml.htm。 – Anon 2010-06-15 18:37:55