惊呆了,原来JavaIO如此简单【奔跑吧!JAVA】

网友投稿 536 2022-05-28

前言:

群里有大佬说想让我写一篇NIO,一直也没写,但是和同事聊天也说对Java的IO不是很清晰,因此今天就写下Java的IO,先打个基础,下次写NIO,我们开始吧

一、IO底层是怎么回事?

二、梳理类的结构

三、IO类大点兵

四、来波实例展示

import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * 拷贝文件 * @author 香菜 */ public class CopyFileWithStream { public static void main(String[] args) { int b = 0; String inFilePath = "D:\wechat\A.txt"; String outFilePath = "D:\wechat\B.txt"; try (FileInputStream in = new FileInputStream(inFilePath); FileOutputStream out = new FileOutputStream(outFilePath)) { while ((b = in.read()) != -1) { out.write(b); } } catch (IOException e) { e.printStackTrace(); } System.out.println("文件复制完成"); } }

惊呆了,原来JavaIO如此简单【奔跑吧!JAVA】

package org.pdool.iodoc; import java.io.*; /** * 拷贝文件 * * @author 香菜 */ public class CopyFileWithBuffer { public static void main(String[] args) throws Exception { String inFilePath = "D:\wechat\A.txt"; String outFilePath = "D:\wechat\B.txt"; try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inFilePath)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outFilePath))) { byte[] b = new byte[1024]; int off = 0; while ((off = bis.read(b)) > 0) { bos.write(b, 0, off); } } } }

import java.util.Scanner; public class TestScanner { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()){ System.out.println(scanner.nextLine()); } } }

总结:

而Reader/Writer则是用于操作字符,增加了字符编解码等功能,适用于类似从文件中读取或者写入文本信息。本质上计算机操作的都是字节,不管是网络通信还是文件读取,Reader/Writer相当于构建了应用逻辑和原始数据之间的桥梁。

Buffered等带缓冲区的实现,可以避免频繁的磁盘读写,进而提高IO处理效率。

记住IO流的设计模式是装饰器模式,对流进行功能升级。

stream,reader ,buffered 三个关键词记住

【奔跑吧!JAVA】有奖征文火热进行中:https://bbs.huaweicloud.com/blogs/265241

Java 任务调度

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:TL138/1808/6748-EVM开发板硬件说明(2)
下一篇:为了OFFER系列 | 牛客网美团点评数据分析刷题
相关文章