首页 文章

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

提问于
浏览
0

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

  • Build 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");

  • 通过输入流阅读器读取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();

  • 解析通过GSON解析器 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(); 收到的JSON

  • 通过fileoutstream在新属性文件中写入已翻译的值

FileOutputStream foutStream = new FileOutputStream(outFile); foutStream.write(key.getBytes()); foutStream.write("=".getBytes()); foutStream.write(transByte.getBytes());foutStream.write("\n".getBytes());

问题是我在阿拉伯语的新属性文件中写了乱码文本(?????) . 请提出可能的原因 .

1 回答

  • 0

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

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

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

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

    尝试使用自定义字符串连接发出文件格式,正如您所做的那样,是经常重复的灾难处理方法 . 无论是XML,JSON还是简单的属性文件,都很容易忽略需要转义序列等的特殊情况 . 使用设计用于发出格式的库 .

相关问题