常用的几种流


  • 数据在两设备间的传输称为流,流的本质是数据传输,根据数据传输特性将流抽象为各种类,方便更直观的进行数据操作。
    按照流向,流分为:输入流(外设到电脑),输出流(电脑到外设)。
    按照处理数据的单位,流分为:字节流,字符流。

下面为几种常用的流使用方法:


public class 推荐使用的 {
    // 图片、视频
    private static void 如果读取的是二进制数据() throws IOException {
        try (InputStream is = new FileInputStream("某张图片.jpg")) {
            byte[] buf = new byte[8192];
            int len;

            while ((len = is.read(buf)) != -1) {
                // 使用读到的数据 buf[0, len)
            }
        }
    }

    // 图片、视频
    private static void 如果写的是二进制数据() throws IOException {
        try (OutputStream os = new FileOutputStream("某张图片.jpg")) {
            byte[] buf = new byte[1024];    // 根据业务场景得到的数据
            for (int i = 0; i < 5; i++) {
                // 如果需要多次写
                int start = 5;
                int len = 10;
                os.write(buf, start, len);
            }

            os.flush();
        }
    }

    // 读的是文本(无论是否是中文、还是英文、还是其他文本
    private static void 如果读取的是字符数据() throws IOException {
        try (InputStream is = new FileInputStream("某篇文章.txt")) {
            try (InputStreamReader isReader = new InputStreamReader(is, "UTF-8")) {
                try (Scanner scanner = new Scanner(isReader)) {
                    // 我想要按行读
                    while (scanner.hasNextLine()) {
                        String line = scanner.nextLine();
                    }
                }
            }
        }
    }

    // 写的文本
    private static void 如果写的是字符数据() throws IOException {
        try (OutputStream os = new FileOutputStream("某篇文章.txt")) {
            try (OutputStreamWriter osWriter = new OutputStreamWriter(os, "UTF-8")) {
                try (PrintWriter printWriter = new PrintWriter(osWriter)) {
                    printWriter.println("1");
                    printWriter.printf("2");
                    printWriter.print("3");
                    printWriter.format("4");

                    printWriter.flush();
                }
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值