mus*_*ibs 0 java utf-8 character-encoding
在我的应用程序中,我正在读取一个包含一些阿拉伯字符(编码为ISO 8859-6)的文件,我正在将其转换为UTF-8编码并使用BufferedWriter. 但是,在我新生成的文件中,我看不到阿拉伯字符,而是出现了几个问号。
来自我的原始文件的片段
Sample Data//????
Another line,
One more line/????
Run Code Online (Sandbox Code Playgroud)
来自生成文件的片段
Sample Data//????
Another line,
One more line/????
Run Code Online (Sandbox Code Playgroud)
我正在使用以下方法进行转换:
private String convertCharSet(String data, String sourceCharacterCode, String destinationCharacterCode) throws UnsupportedEncodingException
{
Charset charsetSource = Charset.forName(sourceCharacterCode);
Charset charsetDestination = Charset.forName(destinationCharacterCode);
ByteBuffer inputByteBuffer = ByteBuffer.wrap(data.getBytes(sourceCharacterCode));
CharBuffer charBuffer = charsetSource.decode(inputByteBuffer);
ByteBuffer outputByteBuffer = charsetDestination.encode(charBuffer);
return new String(outputByteBuffer.array(), destinationCharacterCode);
}
Run Code Online (Sandbox Code Playgroud)
我正在使用以下方法写入文件
public static void writeToFile(String filePath, String data) throws IOException
{
BufferedWriter out = null;
try
{
out = new BufferedWriter(new FileWriter(new File(filePath)));
out.write(data);
out.flush();
}
finally
{
out.close();
}
}
Run Code Online (Sandbox Code Playgroud)
观察
在 中notepad++,我以ISO 8859-6格式打开文件,我可以看到阿拉伯字符。我将它转换为UTF-8usingConvert to UTF-8选项,转换后我可以在那里看到阿拉伯字符。
我已经调试了我的程序eclipse,在转换之前我可以看到阿拉伯字符,在转换之后UTF-8我也可以看到阿拉伯字符。但是一旦将内容写入文件,我就会得到这些?标记而不是阿拉伯字符。
笔记
-Dfile.encoding=ISO-8859-6作为虚拟参数。任何帮助是极大的赞赏。
在 Java(相对于其他语言)文本中,String/Char/Reader/Writer是 Unicode,能够组合所有脚本。
因此转换必须不是在字符串之间进行,而是在字符串和二进制数据之间进行byte[]/InputStream/OutputStream。
Path sourcePath = Paths.get("C:/data/arab.txt");
byte[] sourceData = Files.readAllBytes(sourcePath);
String s = new String(sourceData, "ISO-8859-6");
byte[] targetData = s.getBytes(StandardCharsets.UTF_8);
Files.write(targetData, targetPath, StandardOpenOption.REPLACE_EXISTING);
Run Code Online (Sandbox Code Playgroud)
如您所见,Java 中的概念很简单 - 一旦知道。
FileWriter/FileReader 是旧的实用程序类,它们使用默认平台编码。不便携。仅适用于本地文件。
在 java 1.6 中(没有异常处理):
File sourceFile = ...
File targetFile = ...
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(sourceFile), "ISO-8859-6"));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
new FileOuputStream(targetFile), "UTF-8"));
for (;;) {
String line = in.readLine();
if (line == null) {
break;
}
out.write(line);
out.write("\r\n"); // Windows CR+LF.
}
out.close();
in.close();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1969 次 |
| 最近记录: |