JavaIO:文件字节流

InputStream

单个字节逐一读取

public class testInputStream {
    public static void main(String[] args){
     File file=new File("E:\\Idea  workspace\\IdeaProjects\\FirstMoudle\\src\\cn\\xjh\\io\\text");//也可以用相对路径
     InputStream is=null;
     int temp;//得到返回值,范围值为ASCII码值,可以转换为char显示
        try {
            is=new FileInputStream(file);//多态定义一个子类
            while((temp=is.read())!=-1){
                System.out.print((char)temp);//逐一打印
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

也可以定义一个缓冲数组 byte[] flush=new byte[1024] ,然后is.read(flush)每一次按数组大小1024字节读取。

public class testInputStream {
    public static void main(String[] args){
     File file=new File("E:\\Idea  workspace\\IdeaProjects\\FirstMoudle\\src\\cn\\xjh\\io\\text");//从该文件中读取内容。
     InputStream is=null;
     byte[] flush=new byte[1024];//缓冲数组
        int len;//得到返回值,返回值是当前接受的字节个数
        try {
            is=new FileInputStream(file);//若文件不存在则抛出异常
            while((len=is.read(flush))!=-1){//将文件内容按缓冲数组大小读入缓存数组内,当返回为-1时全部读取完
                String str=new String(flush,0,len,"utf8");//返回值len是当前接收字节个数,结束时返回-1
                System.out.println(str);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

OutputStream

 public static void main(String[] args) {
        File src=new File("text01.txt");//定义一个等待写入的文件,如果不存在则自动创建
        OutputStream os=null;

        try {
            os=new FileOutputStream(src,true);//将对象数据写入文件src内//
            /*FileOutputStream(File file, boolean append) ,true代表不覆盖文件之前的内容,在后面添加。flase则覆盖重写*/
            String s="四毛和傻曈";
            byte[] datas=s.getBytes();
            os.write(datas,0,datas.length);//数据,在数据偏移开始,写入字节数
            os.flush();//刷新此输出流并强制写出所有缓冲的输出字节
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值