Java--流

发布于:2024-07-25 ⋅ 阅读:(152) ⋅ 点赞:(0)

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");
    }


网站公告

今日签到

点亮在社区的每一天
去签到