LineNumberReader支持UTF-8编码

时间:2012-03-12 05:56:42

标签: utf-8 java-io

当我尝试从文件中读取文本时,使用LineNumberReader无法正确显示基础文本

尝试从文件中读取的文字 -

¥ · £ · € · $ · ¢ · ₡ · ₢ · ₣ · ₤ · ₥ · ₦ · ₧ · ₨ · ₩ · ₪ · ₫ · ₭ · ₮ · ₯ · ₹

示例代码 -

FileInputStream fis = null;
    try {
        fis = new FileInputStream("C:\\Users\\JavaUser4\\Desktop\\checkImort.txt");
        InputStreamReader streamReader = new InputStreamReader(fis, "UTF-8");
        LineNumberReader reader = new LineNumberReader(streamReader);
        String sLine = reader.readLine();
        System.out.println(sLine);
    } catch (Exception ex) {
    } finally {
        try {
            fis.close();
        } catch (IOException ex) {
        }
    }

输出 -

? ? ? ? ? ? $ ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

请使用LineNumberReader帮助您正确阅读本文。我更喜欢留在LineNumberReader因为我根据我的要求使用RandomAccessFile这是一个完美的解决方案

  • 打开包含UTF-8编码文本的文件。
  • 设置我们需要开始读取文件的行号。
  • 从文本文件中读取25行。
  • 获取抵消的最后位置。
  • 退出。
  • 再次打开文件。
  • 设置行号,我们需要从同一文件开始读取下25行。
  • 从文本文件中读取25行。
  • 获取最后一次偏移。
  • 等等。

缺点是RandomAccessFile不支持UTF-8编码,我转移到LineNumberReader但这里也发生了同样的情况。请帮忙。

1 个答案:

答案 0 :(得分:0)

您正在正确读取(假设文件实际上采用UTF-8编码)。

问题在于输出。

您正在写入的输出流可能被配置为输出为ISO-8859-1或其变体之一(我猜你在Windows上运行它,因为这是Windows上的常见问题)。

注意输出“?”通常是由于某些字符无法在给定的编码中表示。所以你的String包含正确的字符(你应该能够在调试器中检查它),但是输出流不能写出来。