文件字节流

FileInputStream:通过字节的方式读取文件。

FileOutputStream:通过字节的方式写出或追加数据到文件。

public class IOTest03 {
    public static void main(String[] args) {
        InputStream is=null;
        File file=new File("a.txt");//数据源
        try {
            is=new FileInputStream(file);//选择流
            int len=-1;
            byte[] bytes=new byte[5];//五个一组,进行读取
            while((len=is.read(bytes))!=-1){//循环读取内容
                String string=new String(bytes,0,len);//字节数组-->字符串
                System.out.println(string);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(is!=null){//如果is读取到了内容,证明流打开了需要关闭
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 

public class IOTest04 {
    public static void main(String[] args) {
        File file=new File("b.txt");//创建源
        OutputStream os=null;
        try {
            //选择流,true表明每次执行,原来的语句不覆盖
            os=new FileOutputStream(file,true);
            String str="Hello World!\r\n";//换行
            byte[] bytes=str.getBytes();//字符串-->字节数组
            os.write(bytes,0,bytes.length);//将bytes数组的内容输入
            os.flush();//刷新缓冲
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                if(os!=null){
                    os.close();//关闭流
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值