文章目录

  • 缓冲流
  • 转换流
  • 标准输入输出流
  • 打印流
  • 数据流
  • 对象流
  • 随机存取文件流
  • Java NIO

缓冲流

为了提高数据读写的速度,Java API提供了带缓冲功能的流类,在使用这些流类时,会创建一个内部缓冲区数组,缺省使用8192个字节(8Kb)的缓冲区。


缓冲流要“套接”在相应的节点流之上,根据数据操作单位可以把缓冲流分为:
BufferedInputStreamBufferedOutputStream
BufferedReaderBufferedWriter

当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区。当使用BufferedInputStream读取字节文件时,BufferedInputStream会一次性从文件中读取8192个(8Kb),存在缓冲区中,直到缓冲区装满了,才重新从文件中读取下一个8192个字节数组。

向流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区写满,
BufferedOutputStream才会把缓冲区中的数据一次性写到文件里。使用方法
flush()可以强制将缓冲区的内容全部写入输出流。

关闭流的顺序和打开流的顺序相反。只要关闭最外层流即可,关闭最外层流也
会相应关闭内层节点流。

flush()方法的使用:手动将buffer中内容写入文件。使用带缓冲区的流对象的close()方法,不但会关闭流,还会在关闭流之前刷新缓冲区,相当于自动调用了flush()方法,关闭后不能再写出。


以字节流BufferedInputStreamBufferedOutputStream示例具体操作:

import java.io.*;/*** @Author: Yeman* @Date: 2021-09-25-22:36* @Description:*/
public class BufferedTest {public static void main(String[] args) {FileInputStream fis = null;FileOutputStream fos = null;BufferedInputStream bfi = null;BufferedOutputStream bfo = null;try {//1、实例化File对象,指定文件File inFile = new File("IO\\input.jpg");File outFile = new File("IO\\output.jpg");//2、创建节点流(文件流)对象fis = new FileInputStream(inFile);fos = new FileOutputStream(outFile);//3、创建处理节点流的缓冲流对象bfi = new BufferedInputStream(fis);bfo = new BufferedOutputStream(fos);//4、通过缓冲流进行读写操作byte[] bytes = new byte[1024];int length = bfi.read(bytes);while (length != -1){bfo.write(bytes,0,length);length = bfi.read(bytes);}} catch (IOException e) {e.printStackTrace();} finally {//5、关闭外层流,内存流便自动关闭try {if (bfi != null) bfi.close();} catch (IOException e) {e.printStackTrace();}try {if (bfo != null) bfo.close();} catch (IOException e) {e.printStackTrace();}}}
}

转换流

转换流提供了在字节流和字符流之间的转换。

InputStreamReader:将InputStream转换为Reader(字节转为字符输入)
OutputStreamWriter:将Writer转换为OutputStream(字节转为字符输出)

字节流中的数据都是字符时,转成字符流操作更高效。使用转换流来处理文件乱码问题,实现编码和解码的功能。

InputStreamReader:
实现将字节的输入流按指定字符集转换为字符的输入流。需要和InputStream“套接”。
构造器:
public InputStreamReader(InputStream in)
public InputSreamReader(InputStream in,String charsetName)
OutputStreamWriter:
实现将字符的输出流按指定字符集转换为字节的输出流。需要和OutputStream“套接”。
构造器:
public OutputStreamWriter(OutputStream out)
public OutputSreamWriter(OutputStream out,String charsetName)

import java.io.*;/*** @Author: Yeman* @Date: 2021-09-26-20:13* @Description:*/
public class Test {public static void main(String[] args) {InputStreamReader isr = null;OutputStreamWriter osw = null;try {//1、指明输入输出文件File inFile = new File("IO\\hi.txt");File outFile = new File("IO\\hello.txt");//2、提供字节节点流FileInputStream fis = new FileInputStream(inFile);FileOutputStream fos = new FileOutputStream(outFile);//3、提供转换流isr = new InputStreamReader(fis,"gbk");osw = new OutputStreamWriter(fos,"utf-8");//4、读写操作char[] chars = new char[10];int len = isr.read(chars);while (len != -1){osw.write(chars,0,len);len = isr.read(chars);}} catch (IOException e) {e.printStackTrace();} finally {//5、关闭外层流try {if (osw != null) osw.close();} catch (IOException e) {e.printStackTrace();}try {if (isr != null) isr.close();} catch (IOException e) {e.printStackTrace();}}}
}

标准输入输出流

System.inSystem.out分别代表了系统标准的输入和输出设备
默认输入设备是:键盘,输出设备是:显示器(控制台)

System.in的类型是InputStream
System.out的类型是PrintStream,其是OutputStream的子类

重定向:通过System类的setIn()setOut()方法对默认设备进行改变:
public static void setIn(InputStream in)
public static void setOut(PrintStream out)

import java.io.*;/*** @Author: Yeman* @Date: 2021-09-26-20:13* @Description:*/
public class Test {public static void main(String[] args) {BufferedReader bis = null;try {//1、提供转换流(System.in是字节流,将其转换为字符流)System.out.println("请输入信息(退出输入e或exit):");InputStreamReader isr = new InputStreamReader(System.in);//2、提供缓冲流将输入的一行读取bis = new BufferedReader(isr);//3、读操作String s = null;while ((s = bis.readLine()) != null){if ("e".equalsIgnoreCase(s) || "exit".equalsIgnoreCase(s)){System.out.println("程序结束,退出程序!");break;}System.out.println("==" + s.toUpperCase());System.out.println("继续输入(退出输入e或exit):");}} catch (IOException e) {e.printStackTrace();} finally {//4、关闭外层流try {if (bis != null) bis.close();} catch (IOException e) {e.printStackTrace();}}}
}

打印流

实现将基本数据类型的数据格式转化为字符串输出。

打印流:PrintStreamPrintWriter
提供了一系列重载的print()println()方法,用于多种数据类型的输出:
PrintStream和PrintWriter的输出不会抛出IOException异常,
PrintStream和PrintWriter有自动flush功能,
PrintStream打印的所有字符都使用平台的默认字符编码转换为字节
在需要写入字符而不是写入字节的情况下,应该使用PrintWriter类。

System.out返回的是PrintStream的实例。

常与System.out搭配使用,可以不在控制台输出,而是输出到指定位置:

import java.io.*;/*** @Author: Yeman* @Date: 2021-09-26-20:13* @Description:*/
public class Test {public static void main(String[] args) {PrintStream ps = null;try {FileOutputStream fos = new FileOutputStream(new File("IO\\text.txt"));
// 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)ps = new PrintStream(fos, true);if (ps != null) {// 把标准输出流(控制台输出)改成文件System.setOut(ps);}for (int i = 0; i <= 255; i++) { // 输出ASCII字符System.out.print((char) i);if (i % 50 == 0) { // 每50个数据一行System.out.println(); // 换行}}} catch (FileNotFoundException e) {e.printStackTrace();} finally {if (ps != null) {ps.close();}}}
}

数据流

为了方便地操作Java语言的基本数据类型和String的数据,可以使用数据流。

数据流有两个类:(用于读取和写出基本数据类型、String类的数据)
DataInputStreamDataOutputStream
分别“套接”在 InputStream 和 OutputStream 子类的流上。

import java.io.*;/*** @Author: Yeman* @Date: 2021-09-26-20:13* @Description:*/
public class Test {public static void main(String[] args) {//写DataOutputStream dos = null;try {dos = new DataOutputStream(new FileOutputStream("IO\\test.txt"));dos.writeUTF("叶绿体");dos.writeInt(22);dos.writeBoolean(true);} catch (IOException e) {e.printStackTrace();} finally {try {if (dos != null) dos.close();} catch (IOException e) {e.printStackTrace();}}//读DataInputStream dis = null;try {dis = new DataInputStream(new FileInputStream("IO\\test.txt"));//注意读的顺序要和写的顺序一样String name = dis.readUTF();int age = dis.readInt();boolean isMan = dis.readBoolean();System.out.println(name + age + isMan);} catch (IOException e) {e.printStackTrace();} finally {try {if (dis != null) dis.close();} catch (IOException e) {e.printStackTrace();}}}
}

对象流

ObjectInputStreamOjbectOutputSteam

用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。

序列化:用ObjectOutputStream类保存基本类型数据或对象的机制
反序列化:用ObjectInputStream类读取基本类型数据或对象的机制

ObjectOutputStreamObjectInputStream不能序列化statictransient修饰的成员变量。

实现Serializable或者Externalizable两个接口之一的类的对象才可序列化,关于对象序列化详见:序列化

可序列化对象:

import java.io.Serializable;/*** @Author: Yeman* @Date: 2021-09-27-8:27* @Description:*/class pet implements Serializable {public static final long serialVersionUID = 999794470754667999L;private String name;public pet(String name) {this.name = name;}@Overridepublic String toString() {return "pet{" +"name='" + name + '\'' +'}';}
}public class Person implements Serializable {public static final long serialVersionUID = 6849794470754667999L;private String name;private int age;private pet pet;public Person(String name, int age, pet pet) {this.name = name;this.age = age;this.pet = pet;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +", pet=" + pet +'}';}
}

序列化(ObjectOutputStream):

import java.io.*;/*** @Author: Yeman* @Date: 2021-09-26-20:13* @Description:*/
public class Test {public static void main(String[] args) {ObjectOutputStream oos = null;try {oos = new ObjectOutputStream(new FileOutputStream("IO\\test.txt"));oos.writeUTF(new String("你好世界!"));oos.flush();oos.writeObject(new Person("Lily",20,new pet("Xinxin")));oos.flush();} catch (IOException e) {e.printStackTrace();} finally {try {if (oos != null) oos.close();} catch (IOException e) {e.printStackTrace();}}}
}

反序列化(ObjectInputStream):

import java.io.*;/*** @Author: Yeman* @Date: 2021-09-26-20:13* @Description:*/
public class Test {public static void main(String[] args) {ObjectInputStream ois = null;try {ois = new ObjectInputStream(new FileInputStream("IO\\test.txt"));String s = ois.readUTF();Person o = (Person) ois.readObject();System.out.println(o.toString());} catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();} finally {if (ois != null) {try {ois.close();} catch (IOException e) {e.printStackTrace();}}}}
}

随机存取文件流

RandomAccessFile声明在java.io包下,但直接继承于java.lang.Object类。并且它实现了DataInputDataOutput这两个接口,也就意味着这个类既可以读也可以写。

RandomAccessFile类支持 “随机访问” 的方式,程序可以直接跳到文件的任意地方来读写文件:①支持只访问文件的部分内容②可以向已存在的文件后追加内容③若文件不存在,则创建④若文件存在,则从指针位置开始覆盖内容,而不是覆盖文件。

RandomAccessFile对象包含一个记录指针,用以标示当前读写处的位置,RandomAccessFile类对象可以自由移动记录指针:
long getFilePointer():获取文件记录指针的当前位置
void seek(long pos):将文件记录指针定位到 pos 位置

构造器:
public RandomAccessFile(File file, String mode)
public RandomAccessFile(String name, String mode)
创建 RandomAccessFile 类实例需要指定一个 mode 参数,该参数指定 RandomAccessFile 的访问模式:
如果模式为只读r。则不会创建文件,而是会去读取一个已经存在的文件,如果读取的文件不存在则会出现异常。 如果模式为rw读写。如果文件不存在则会去创建文件,如果存在则不会创建。

import java.io.*;/*** @Author: Yeman* @Date: 2021-09-26-20:13* @Description:*/
public class Test {public static void main(String[] args) {RandomAccessFile r1 = null;RandomAccessFile rw = null;try {r1 = new RandomAccessFile("IO\\input.jpg", "r");rw = new RandomAccessFile("IO\\output.jpg", "rw");byte[] bytes = new byte[1024];int len = r1.read(bytes);while (len != -1){rw.write(bytes,0,len);len = r1.read(bytes);}} catch (IOException e) {e.printStackTrace();} finally {try {if (rw != null) rw.close();} catch (IOException e) {e.printStackTrace();}try {if (r1 != null) r1.close();} catch (IOException e) {e.printStackTrace();}}}
}

Java NIO

Java NIO (New IO,Non-Blocking IO)是从Java 1.4版本开始引入的一套新的IO API,可以替代标准的Java IO API。NIO与原来的IO有同样的作用和目的,但是使用的方式完全不同,NIO支持面向缓冲区的(IO是面向流的)、基于通道的IO操作,NIO将以更加高效的方式进行文件的读写操作。

Java API中提供了两套NIO,一套是针对标准输入输出NIO,另一套就是网络编程NIO。

随着 JDK 7 的发布,Java对NIO进行了极大的扩展,增强了对文件处理和文件系统特性的支持,以至于我们称他们为 NIO.2。因为 NIO 提供的一些功能,NIO已经成为文件处理中越来越重要的部分。

早期的Java只提供了一个File类来访问文件系统,但File类的功能比较有限,所提供的方法性能也不高。而且,大多数方法在出错时仅返回失败,并不会提供异常信息。
NIO. 2为了弥补这种不足,引入了Path接口,代表一个平台无关的平台路径,描述了目录结构中文件的位置。Path可以看成是File类的升级版本,实际引用的资源也可以不存在。

在以前IO操作都是这样写的:

import java.io.File;
File file = new File("index.html");

但在Java7 中,可以这样写:

import java.nio.file.Path;
import java.nio.file.Paths;
Path path = Paths.get("index.html");

同时,NIO.2在java.nio.file包下还提供了Files、Paths工具类,Files包含了大量静态的工具方法来操作文件;Paths则包含了两个返回Path的静态工厂方法。

Paths 类提供的静态 get() 方法用来获取 Path 对象:
static Path get(String first, String … more) : 用于将多个字符串串连成路径
static Path get(URI uri): 返回指定uri对应的Path路径



让你的数据和对象有源有出路,一文打尽,Java常用IO流处理流(处理字节流文件流)缓冲流、转换流、对象流等相关推荐

  1. 第13天 缓冲、转换、对象(序列化)和打印流

    缓冲.转换.对象(序列化)和打印流 第一章 缓冲流 1.1 概述 1.2 字节缓冲流 1.3 字符缓冲流 1.4 练习:文本排序 第二章 转换流 2.1 字符编码和字符集 字符编码 字符集 2.2 编 ...

  2. 对象存储2:数据存储类型-文件存储、块存储、对象存储详解

    上一篇介绍了传统存储的几个常用类型,本篇主要介绍云平台用到的常用存储类型,分别是文件存储.块存储和对象存储. 这种分类是以数据存储的方式来命名的,体现了不同的数据存储格式.文件存储会以文件和文件夹的层 ...

  3. python 爬虫(七)lxml模块 + lxml数据提取(字符串的xml/html文件--转换--element对象--转换--字符串)调用XPath方法筛选数据 + 案例(扇贝 酷狗 网易云音乐)

    爬虫小知识:爬取网站流程 确定网站哪个url是数据的来源. 简要分析一下网站结构,查看数据一般放在哪里. 查看是否有分页,解决分页的问题. 发送请求,查看response.text里面是否有我们想要的 ...

  4. java常用的集合对象_java常用实体类、集合类

    java常用实体类.集合类 [转自51cto博客jichangwei的BLOG] 1:String类,字符串是常量,他们的值在创建之后不能更改,可以共享. equals()用来比较两个字符串的值,== ...

  5. java查看对象锁级别_对象级别锁 vs 类级别锁(Java)

    前言 对于多线程(并发)和Spring Boot这两块在同步进行学习中,在看到使用synchronized关键字使操作同步时,看到和C#中不一样的东西,所以这里呢,就深入学习了下,若有错误之处,还望指 ...

  6. php把数组转换成对象,php怎么将数组转换成对象

    echoecho() 函数输出一个或多个字符串.注释:echo() 函数实际不是一个函数,所以您不必对它使用括号.然而,如果您想要传多于一个参数给 echo(),使用括号将会生成解析错误.print ...

  7. Java基础-IO流对象之数据流(DataOutputStream与DataInputStream)

    Java基础-IO流对象之数据流(DataOutputStream与DataInputStream) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.数据流特点 操作基本数据类型 ...

  8. Java面试宝典系列之基础面试题String、变量、类与对象、集合类、SSH(二)

    作者:egg 邮箱:xtfggef@gmail.com 微博:http://weibo.com/xtfggef 博客:http://blog.csdn.net/zhangerqing(转载请说明出处) ...

  9. Java面试宝典系列之基础面试题String、变量、类与对象、集合类、SSH(一)

    作者:egg 邮箱:xtfggef@gmail.com 微博:http://weibo.com/xtfggef 博客:http://blog.csdn.net/zhangerqing(转载请说明出处) ...

最新文章

  1. HTML5 javascript修改canvas的大小
  2. 编码格式经典书籍--代码整洁之道
  3. Zephyr内核到1.5版本的改进
  4. nginx日志中文变成类似\xE9\xA6\x96\xE9\xA1\xB5-\xE6\x8E\xA8\xE8\x8D\x90的东西,治本方案
  5. BringWindowToTop
  6. 第二十九章:学校招生
  7. python线程按照顺序执行_Python3多线程之间的执行顺序问题
  8. Ubuntu 16.04安装PPA图形化管理工具Y PPA Manager
  9. Mysql基础之 ALTER命令
  10. 洪恩软件c语言,C语言英才宝典app下载
  11. Rider 使用Emmylua 代码提示
  12. 程序员 做头发 奇遇记
  13. 【现代密码学】作业一
  14. java mybatis优点_mybatis优缺点是什么?有哪些优点和缺点?
  15. 跟狗屎一样的代码,到底该如何重构?
  16. 【友盟+】国庆假期旅游类APP使用报告(下)
  17. 大人,时代变了——手游抽卡异军突起
  18. 计算机二进制转化教案及ppt,计算机《数制与编码-进制转换》公开课教案.doc
  19. 给刚出社会的您关于社会的几点建议与看法
  20. CSR8675的DSP学习笔记——a2dp_sink工程的matlab仿真

热门文章

  1. Java接口的防御性API演进
  2. 使用Jolokia和JMX进行客户端服务器监视
  3. 集成测试CDI 1.0和Spring 3.1中的作用域bean
  4. Java:对Java SE 6和Java SE 7的客户端和桌面部分的改进!
  5. nproc是什么意思_top/htop内容的含义
  6. 高速信号传输约翰逊 pdf_高速数字电路仿真设计与测试技术发展趋势综述 (一)...
  7. 21朵水仙花算法java,柏拉图说,如果你有两块面包,你应当用一块去换一朵水仙花。。。。。...
  8. 杭州电子科技大学保研计算机,杭州电子科技大学计算机学院计算机科学与技术(一级学科)保研细则...
  9. 如何正确认识C语言在当今编程领域的地位
  10. vector怎么按字段查询顺序输出_7大查询匹配类函数,一次给你总结好