lo流,字节

什么是io流?

在 Java 中所有数据都是使用流读写的。流是一组有序的数据序列,将数据从一个地方带到另一个地方。根据数据流向的不同,可以分为输入(Input)流和输出(Output)流两种。

 

 字节输入流【InputStream】

 

1.关闭此输入流并释放与此流相关的任何系统资源:public void close();
2.从输入流读取数据的下一个字节:public abstract int read();
3.从输入流中读取一些字节数,并将他们存储到字节数组b中:public int read(byte[]b);

java.io.FileInputStream 类是文件输入流,从文件中读取字节

public static void main(String[] args) throws IOException {
        //输入流:内存的内容输出到文件(写操作)   输出流:文件内容输入到内存中(读操作)
        File f1=new File("C:/aa");
        f1.mkdirs();
        File f2=new File(f1,"a.txt");
        f2.createNewFile();
        InputStream input= new FileInputStream(f2);
        //读取文件的一个字符,然后把字符转换为对于的数字返回,如果读取到文件尾部,返回-1
        int n;
        while((n=input.read())!=-1){
            System.out.println((char)n);
        }
    }

使用read(byte [] b)   缓冲区循环读取内容

public static void main(String[] args) throws IOException {
        //输入流:内存的内容输出到文件(写操作)   输出流:文件内容输入到内存中(读操作)
        File f1=new File("C:/aa");
        f1.mkdirs();
        File f2=new File(f1,"a.txt");
        f2.createNewFile();
        InputStream input= new FileInputStream(f2);
        //读取文件的一个字符,然后把字符转换为对于的数字返回,如果读取到文件尾部,返回-1
        int n;
        byte[] b=new byte[10];
        
        //使用read(byte [] b) 缓冲区循环读取内容
        while((n=input.read(b))!=-1){
            String s=new String(b,0,n);//从0开始,截取有效的字节n
            System.out.println(s);
 
            }
    }

1.通过scanner键盘输出内容

public static void main(String[] args) throws IOException {
        //输入流:内存的内容输出到文件(写操作)   输出流:文件内容输入到内存中(读操作)
        File f1=new File("C:/aa");
        f1.mkdirs();
        File f2=new File(f1,"b.txt");
        f2.createNewFile();
 
        OutputStream out=new FileOutputStream(f2,true);
 
 
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入:");
        String msg=sc.next();
        byte[]bytes =msg.getBytes();//获取字符串,解析成btye数组
        System.out.println(Arrays.toString(bytes));
        out.write(bytes);
 
    }

2.直接输出指定内容

public static void main(String[] args) throws IOException {
        //输入流:内存的内容输出到文件(写操作)   输出流:文件内容输入到内存中(读操作)
        File f1=new File("C:/aa");
        f1.mkdirs();
        File f2=new File(f1,"b.txt");
        f2.createNewFile();
 
        OutputStream out=new FileOutputStream(f2,true);
        String msg="爱你就在一瞬间!";
        byte[]bytes =msg.getBytes();//获取字符串,解析成btye数组
        System.out.println(Arrays.toString(bytes));
        out.write(bytes);
 
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值