Reg - 从字节流读取数据

时间:2015-01-31 15:14:56

标签: java

我正在尝试使用字节流读取包含普通Text数据的文件。我理解在字节流中,每个字节将被逐个读取。因此,如果我通过字节流读取文本文件中的数据Hi How are you!!!!!!,那么它应该给我相应的每个字符的Unicode,但它给我一个不同的输出,不映射到utf或ascii等价物

以下是我的计划

package files;

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

public class FileBaiscs {    
    public static void main(String[] args) throws IOException {        
        String strPath = "D:\\Files\\New.txt";  
        File objSrcFile = new File (strPath);           
        if (objSrcFile.exists()==false)
        {   
            System.out.println("The Source File is not Present");
            System.exit(0);
        }       
        FileInputStream objIpStream = new FileInputStream(objSrcFile);          
        while ((objIpStream.read())!=-1)
        {
            System.out.println(objIpStream.read());
        }           
        objIpStream.close();
    }
}

我的控制台中的输出是:

105
72
119
97
101
121
117
33
33
33

新文本文件中的数据为 - Hi How are you!!!!!!

我希望输出是整数,它们相当于每个字符的上限。如果我的理解是错误的,请告诉我。

2 个答案:

答案 0 :(得分:1)

下面

  while ((objIpStream.read())!=-1)
    {
        System.out.println(objIpStream.read());
    }

您正在阅读2个字节而不是1个字节。第一个是在条件中读取,第二个是在循环体中读取。 你应该做的是

byte b;
      while ((b=objIpStream.read())!=-1)
        {
            System.out.println(b);
        }

答案 1 :(得分:0)

你的误解来自你认为字节是字符的事实;他们不是。

为了读取字符,您必须首先将字节转换为字符,这是使用称为字符编码的过程完成的。 InputStream不会执行此操作,但会Reader

因此,请尝试:

final Path path = Paths.get("F:\\Files\\New.txt");

try (
    final BufferedReader reader = Files.newBufferedReader(path,
        StandardCharsets.UTF_8);
) {
    int c;
    while ((c = reader.read()) != -1)
        System.out.println(c);
}

此外,在原始代码中,每个循环读取两个字节

相关问题