从 Google 转换器 API 读取并写入属性文件时出现编码问题

Encoding issue when reading from Google translator API and writing to properties file

我正在使用 Google 翻译器 API 从英语 属性 文件生成阿拉伯语 属性 文件。

  1. 建立 URL 连接并向 URL 发出 GET 请求,传递原始语言、翻译语言和要翻译的值
URLConnection urlCon = null;  
String urlStr = "https://www.googleapis.com/language/translate/v2";
URL url = new URL(urlStr + "?key=" + apikey + "&source=" + origlang + "&target=" + translateToLang + "&q=" + value);  
urlCon = url.openConnection();
urlCon.setConnectTimeout(1000 * 60 * 5);  
urlCon.setReadTimeout(1000 * 60 * 5);  
urlCon.setDoInput(true);  
urlCon.setDoOutput(true);  
urlCon.setUseCaches(false);  
((HttpURLConnection) urlCon).setRequestMethod("GET");  
urlCon.setRequestProperty("Accept-Charset", "UTF-8");
  1. 正在通过输入流 reader 从 URL 连接读取响应。在编码参数中传递 UTF-8。
BufferedReader br = new BufferedReader(new InputStreamReader(((URLConnection) urlCon).getInputStream(), "UTF-8"));  
/* Reading the response line by line */  
StringBuffer responseString = new StringBuffer();   
String nextLine = null;  
while ((nextLine = br.readLine()) != null) {  
    responseString.append(nextLine);  
}  
// if response is null or empty, throw exception  
String response = responseString.toString();
  1. 解析通过 GSON 解析器接收到的 JSON
JsonElement jelement = new JsonParser().parse(response);  
JsonObject jobject = jelement.getAsJsonObject();  
jobject = jobject.getAsJsonObject("data");  
JsonArray jarray = jobject.getAsJsonArray("translations");  
jobject = jarray.get(0).getAsJsonObject();  
String result = jobject.get("translatedText").toString();
  1. 通过 fileoutstream
  2. 将翻译后的值写入新的 属性 文件
FileOutputStream foutStream = new FileOutputStream(outFile);
foutStream.write(key.getBytes());
foutStream.write("=".getBytes());
foutStream.write(transByte.getBytes());foutStream.write("\n".getBytes());

问题是我在阿拉伯语的新 属性 文件中写入乱码文本 (?????)。

当您调用 transByte.getBytes() 时,阿拉伯语翻译使用您的平台默认编码进行编码,如果您的机器配置为 UTF-8 或阿拉伯语,则该编码将仅处理阿拉伯语。否则,字符将被替换为 '�''?' .

创建一个新的 Properties 实例,并使用 setProperty() calls. Then when you store it, 填充它正确的转义将应用于您的阿拉伯语文本,这是必要的,因为 属性 文件使用 ISO- 编码8859-1(西方拉丁字符的编码)。

或者,您可以 store the Properties using a Writer 使用您选择的任何编码配置的实例,但编码不存储在文件本身中,因此您需要元数据或约定来设置正确的再次读取文件时的编码。

最后,您可以 store the Properties in an XML format, 默认使用 UTF-8,或者您可以指定其他编码。文件本身会指定编码,因此更容易为每种语言使用最佳编码。

像您一样尝试使用自定义字符串连接生成文件格式,这是一个经常重复的灾难处方。无论是 XML、JSON 还是简单的属性文件,都非常容易忽略需要转义序列等的特殊情况。请改用旨在发出格式的库。