gpt4 book ai didi

java - 如果 JSON 文件要跨不同平台共享,我是否需要关心编码类型

转载 作者:太空狗 更新时间:2023-10-29 14:20:53 25 4
gpt4 key购买 nike

目前,我正在使用 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;
}

最佳答案

补充一下,FileReader 和 FileWriter 是特定于平台的。更喜欢 ObjectStreams。同样,我的分数不允许我将其作为评论:(

关于java - 如果 JSON 文件要跨不同平台共享,我是否需要关心编码类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16977355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com