【问题标题】:java: FileInputStream.read() reads a byte but can read a char, how come?java: FileInputStream.read() 读取一个字节但可以读取一个字符,怎么会?
【发布时间】:2013-07-04 22:39:43
【问题描述】:

我正在测试FileInputStream,读取文件的文本(dulo.txt),文件中的文本是(ANSI):

你好世界

我使用了 FileInputStream.read() 方法,据我所知 read() 只能读取下一个 byte 并且因为 char 是 2 个字节该程序如何工作?它不应该崩溃吗?

这是我的代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;



class Collections {
  public static void main(String args[]) throws IOException {
      FileInputStream fis= new FileInputStream(new File("dulO.txt"));

      int spazioByte=fis.available();

      for(int i=0; i<spazioByte;i++){
          System.out.println("Byte: "+i+" :"+(char)fis.read());
      }



  }
}

控制台输出:

Byte: 0 :H
Byte: 1 :E
Byte: 2 :L
Byte: 3 :L
Byte: 4 :O
Byte: 5 : 
Byte: 6 :W
Byte: 7 :O
Byte: 8 :R
Byte: 9 :L
Byte: 10 :D

【问题讨论】:

  • 这取决于文件的编码。它是什么?我猜是 ASCII 或 UTF-8...
  • 除非指定,.txt 文件是 ANSI 编码的,每个字符 8 位(1 个字节)。
  • 是的,我已经将它保存在 ANSI 中

标签: java char byte fileinputstream


【解决方案1】:

Char 是非 unicode 格式的 1 个字节。例如,ASCII 格式表示只有 1 个字节的 char。

【讨论】:

  • 其实ASCII是7位。另一方面,ANSI 是 8 位,并且作为文本文件的默认编码更为普遍。
  • @AshwinMukhija - 我承认我认为 ASCII 是 8 位。不过,我的回答仍然有意义:)
  • ASCII 仅支持 128 个字符,即 7 位。 ANSI 支持 256 个字符。你的回答是相关的,是的。 :)
【解决方案2】:

如果你想从文件中读/写字符,你可以使用 Reader/Writer。下面我将展示如何使用 Reader 的简单示例

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class TestReader {

private final static int SIZE = 200;

       public static void main(String[] args) throws IOException {
            Reader reader = new FileReader("1.txt");

            char[] buf = new char[SIZE];
            int count;
            while((count = reader.read(buf)) != -1) {
                for (int i = 0; i < count; i++)
                    System.out.println(buf[i]);
            }
            reader.close();
        }
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多