有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在将文件从ISO 88596转换为UTF8后无法看到阿拉伯语字符

在我的应用程序中,我正在读取一个包含一些阿拉伯语字符的文件(编码为ISO 8859-6),并将其转换为UTF-8编码,然后使用BufferedWriter写回一个新文件。然而,在我新生成的文件中,我看不到阿拉伯字符,而是出现了几个问号

我原始文件中的片段

Sample Data//لمند
Another line,
One more line/لمند

从生成的文件中提取代码片段

 Sample Data//????
 Another line,
 One more line/????

我使用以下方法进行转换:

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);
}

我使用下面的方法写入文件

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();
    }
}

观察结果

  1. notepad++中,我以ISO 8859-6格式打开了文件,我可以 请看阿拉伯字符。我使用Convert to UTF-8选项将其转换为UTF-8,在那里我可以看到转换后的阿拉伯语字符

  2. 我已经在eclipse中调试了我的程序,在转换之前我可以看到阿拉伯语字符,在转换到UTF-8之后我也可以看到阿拉伯语字符。但是一旦内容写入文件,我就会得到那些?标记,而不是阿拉伯字符

注意

  • 在eclipse中,我使用-Dfile.encoding=ISO-8859-6作为虚拟对象 争论
  • 我见过ISO-8859-6 to UTF-8,但那不是 解决我的问题

非常感谢您的帮助


共 (2) 个答案

  1. # 1 楼答案

    在Java(与其他语言相反)文本中,String/Char/Reader/Writer是Unicode,能够组合所有脚本

    因此,转换必须在字符串和二进制数据之间进行,而不是在字符串之间进行

    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);
    

    正如你所看到的,在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();
    
  2. # 2 楼答案

    你的writeToFile方法坏了。您正在打开一个imlicit Writer,但没有指定编码。将使用标准平台编码。你的文件会被破坏。使用接受一种编码的Writer