FileInputStream 原理总结 把文件作为字节流进行读操作

package io;

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

public class IOUtil {

    
/**
 * 读取指定文件内容,按照16进制输出到控制台,为什么要按十六进制?
 * 并且每输出10个byte换行
 * @throws IOException 
 */
    public static void printHex(String filename) throws IOException{
        //把文件作为字节流进行读操作
        FileInputStream in = new FileInputStream(filename);//FileInputStream具体实现了在文件上读取数据
      int b;
      int i=1;
      while((b=in.read())!=-1)//b=in.read()这就是程序核心
      {
          System.out.println(Integer.toHexString(b)+"  ");//将整型b转换成16进制表示的字符串?输出
          if(i++%10==0)
          {
              System.out.println();//每隔十个字节换行
          }
      }
    in.close();
    }

}

思想就是:利用new FileInputStream(filename)把一个文件放入到一个输入流对象in中,调用in.read()方法来逐个字节读取(下面read源码),读取输入流一个字节的数据,返回一个整型int(那么是不是十六进制的整型呢?)。

再调用Integer.toHexString(b)方法将存在b的为int的一个字节的数据转换成一个字符串,然后输出。

总体原理就是,将一篇字符串 放入流进行单个字节的整型读取,然后再转换回字符串单个输出。

 

 

    /**
     * Reads a byte of data from this input stream. This method blocks
     * if no input is yet available.
     *
     * @return     the next byte of data, or <code>-1</code> if the end of the
     *             file is reached.
     * @exception  IOException  if an I/O error occurs.
     */
    public int read() throws IOException {
        return read0();
    }

    private native int read0() throws IOException;

 

 

 

 

//把文件作为字节流进行读操作
FileInputStream in = new FileInputStream(filename);//FileInputStream具体实现了在文件上读取数据

转载于:https://www.cnblogs.com/xuedexin/p/5639329.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值