目前,我正在使用gson
来对对象执行序列化。它在单一平台(Windows)中工作得非常好。
但是,如果我要在不同平台(Windows,Linux,Mac,Android)上共享json文件,我是否需要使用特定类型的编码(UTF-8)? (json文件中会有外语字符)?或者,BufferedWriter / BufferedReader使用的默认编码在所有平台上都是相同的?
public static boolean write(A a, File file) {
final Gson gson = new Gson();
String string = gson.toJson(a);
try {
//If the constructor throws an exception, the finally block will NOT execute
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
try {
writer.write(string);
} finally {
//no need to check for null
//any exceptions thrown here will be caught by
//the outer catch block
writer.close();
}
} catch (IOException ex){
return false;
}
return true;
}
public static A load(File file) {
// Copy n paste from newInstance.
final Gson gson = new Gson();
try {
//If the constructor throws an exception, the finally block will NOT execute
BufferedReader reader = new BufferedReader(new FileReader(file));
try {
return gson.fromJson(reader, A.class);
} finally {
//no need to check for null
//any exceptions thrown here will be caught by
//the outer catch block
reader.close();
}
} catch (IOException ex){
}
return null;
}
答案 0 :(得分:1)
只是添加它,FileReader和FileWriter是特定于平台的。更喜欢ObjectStreams。同样,我的分数不允许我把它作为评论:(