字节输出流与输入流

字节输出流与字节输入流

字节流是原生的操作,是由字节组成。在进行网络数据传输时,所用的数据类型就是字节。
在这里插入图片描述

字节的输出流

OutputStream实现了程序输出内容到文件的处理,由于OutputStream是一个抽象类,所以不能实例化对象,要想实例化对象必须使用子类进行实例化。例如:OutputStream output=new FileOutputStream(file);
下面还文件输出的一个例子:建议文件目录不要选择桌面,选择一个自己容易找到的一个文件目录。

import java.io.*;

public class Test {
    public static void main(String[] args) {
        String directory="E:"+ File.separator+"code"+File.separator+"test.txt";//定义文件目录
        File file=new File(directory);//定义文件
        if(!file.getParentFile().exists()){//此时如果父目录不存在,就创建多级父目录;
            file.getParentFile().mkdirs();//如果父目录不存在,用mkdir()创建,就不能创建成功。mkdir()只能创建当前文件
        }
        OutputStream output = null;//OutputStream是一个抽象类,需要通过子类进行实例化。
        try {
            output = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String str="youaremysunshine";
        try {
            output.write(str.getBytes());//将内容变为字节数组输出
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            output.close();//关闭输出
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

如果想要进行文件追加,就选择FileOutputStream(File file,boolean append)接收追加子类。

字节输入流

InputStream是实现了在程序中读取文件中的内容。同样的,InputSream也是一个抽象类,如果要进行实例化,同样也需要子类,如果要对文件进行处理,则使用FileOutputStream类。
下面是实现文件信息的读取

import java.io.*;
public class Test{
    public static void main(String[] args) {
        String directory="E:"+ File.separator+"code"+File.separator+"test.txt";//定义文件目录
        File file=new File(directory);//定义文件
        if(file.exists()){//需要保证文件存在
            InputStream input= null;//实例化子类
            try {
                input = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            byte[] data=new byte[1024];//每次读取的最大数量
            int len= 0;
            try {
                len = input.read(data);//将数据读取到数组
            } catch (IOException e) {
                e.printStackTrace();
            }
            String result=new String(data,0,len);//将字节数组转为String
            System.out.println("读取的内容:"+result);
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值