JAVA IO 学习日志

   

import java.io.FileInputStream;
import java.io.IOException;
public class InputStream {
    public static void main(String[] args) {
        //要求读取E盘上的file01文件 内容输出到控制台上
        InputStream i=new InputStream();
        i.readFile();
        System.out.println();
        i.readFile01();
    }
    public void readFile(){
        //单个字节的读取
        String Filepath="e:/file01.txt";
        int read=0;
        FileInputStream fis= null;
        try {
            fis = new FileInputStream(Filepath);
            while((read= fis.read())!=-1){
                //读出来的是文本文件中对应的字节本身 比如 a---->97 
                //如果为-1 则文件读取完成
                System.out.print((char)read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //定义字节数组提高读取效率
    public void readFile01(){
        String Filepath="e:/file01.txt";
        int read=0;
        byte by[]=new byte[8];
        FileInputStream fis= null;
        try {
            fis = new FileInputStream(Filepath);
            //此处read返回的是读取的字节长度 
            while((read= fis.read(by))!=-1){
                //read(byte[n])方法一次读取n个长度的字节
                // 比如txt中有一个字符串“abcd” n=4时可以一次性读取到定义的数组中
                System.out.print((new String(by,0,read)));
                //从下标为offset开始 读了多少个就转化成多少个
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 Read方法:

        将文本文件中的字符按字节一次读出 输出-1时 读取完毕

        while循环一次性读取

        提高效率: 预先设定一个字节长度的数组 就相当于一个缓冲

                           一次性读取设定长度的字节数

                              

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值