Java--流

1.InputStream---读

输入流(InputStream)

输入流是Java I/O中用于读取数据的抽象类。它从不同的数据源(如文件、网络等)读取数据,并提供了多种读取数据的方法。

常用方法:

  • int read():读取单个字节的数据。
  • int read(byte[] b):读取一定数量的字节并存储到数组中。
public static void main(String[] args) throws IOException {
        InputStream in = new FileInputStream("D:/ffyc--test/pink.tex");
        while (true) {
            int read = in.read();
            if (read == -1) break;
            System.out.print((char) read);
        }
        in.close();


    }

2.OutputStream---写

输出流(OutputStream)

输出流是Java I/O中用于写入数据的抽象类。它将数据写入到不同的数据接收器(如文件、网络等)。

常用方法:

  • void write(int b):写入单个字节的数据。
  • void write(byte[] b):写入整个字节数组的数据。
public static void main(String[] args) throws IOException {
        final String PATH="D:/ffyc--test/pink.tex";
        File file=new File(PATH);
        OutputStream out =new FileOutputStream(file);//创建流对象

        out.write('o');
        out.write('o');
        out.write('v');
        out.write('e');

        out.flush();
        out.close();

    }

应用---将某个照片或视频拷贝至指定文件夹

public static void main(String[] args) throws IOException {
        InputStream in=new FileInputStream("C:\\Users\\Joy\\Pictures\\Saved Pictures\\微信图片_20240316205958.jpg");
        OutputStream out=new FileOutputStream("D:/ffyc--test/pink.jpg");

        int n=0;
        byte[] buffer=new byte[1024*1024];
        long s1=System.currentTimeMillis();
        while (true){
            if (n==-1) break;
            n=in.read(buffer);
            out.write(buffer);
        }
        long s2=System.currentTimeMillis();
        out.close();
        in.close();
        System.out.println("拷贝耗时: "+(s2-s1)+"ms");
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值