【问题标题】:Reg - Data Read from Byte StreamReg - 从字节流中读取的数据
【发布时间】:2015-01-31 15:14:56
【问题描述】:

我正在尝试使用字节流读取包含普通文本数据的文件。而且我知道在字节流中每个字节都会被一个一个地读取。因此,如果我通过字节流读取文本文件中的数据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!!!!!!

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

【问题讨论】:

    标签: java


    【解决方案1】:

    这里

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

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

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

    【讨论】:

      【解决方案2】:

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

      为了读取字符,您必须首先将字节转换为字符,这是使用称为字符编码的过程完成的。 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);
      }
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-26
        • 2015-12-01
        • 2021-04-03
        • 2011-12-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多