20230310----IO读取文件内容,FileInputStream,输入流(读取read)

该文展示了使用Java的FileInputStream进行文件读取的三种方法。第一种逐个字符读取,第二种通过指定长度的字节数组读取,第三种同样使用字节数组但考虑了读取长度。每种方法都处理了可能的FileNotFoundException和IOException。

下面有三种读取方法:

public class FileOutputDemo3 {
    public static void main(String[] args) {
        File file=new File("D:/20230310/a.txt");
        InputStream in=null;
        try {
            //读取流对象
            in=new FileInputStream(file);
            //读取数据
            int len=0;//第一种
            while((len=in.read())!=-1){
                char read=(char)len;//将ASC转化为char类型
                System.out.print(read); }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
public class FileOutputDemo3 {
    public static void main(String[] args) {
        File file=new File("D:/20230310/a.txt");
        InputStream in=null;
        try {
            //读取流对象
            in=new FileInputStream(file);
            //读取数据
            int len=0;//第二种
            byte[] bytes=new byte[6];
            while ((len=in.read(bytes))!=-1){
                for (int i = 0; i < len; i++) {
                    System.out.print((char)bytes[i]);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
public class FileOutputDemo3 {
    public static void main(String[] args) {
        File file=new File("D:/20230310/a.txt");
        InputStream in=null;
        try {
            //读取流对象
            in=new FileInputStream(file);
            //读取数据
            int len=0;//第三种遍历文件内容
            byte[] bytes=new byte[10];
            int leng=in.read(bytes,0,bytes.length);
            for (int i = 0; i < leng; i++) {
                System.out.print((char) bytes[i]);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

总结:第二种遍历方法数组长度必须大于0,例如长度为1的时候,会将一个字符一个字符的赋值给bytes,然后一个一个输出。

第三种遍历,

      当里面只有一行的时候,需要看文件这行有多少个字符,去设置数组长度,然后根据      in.read(bytes,0,bytes.length)返回leng,读取的长度。

      当文件里面有多行的时候,读取的时候,一行是多两个字符的,长度必须是字符数+2*(行数-1)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值