博客
关于我
Java学习笔记(九)之IO操作二
阅读量:791 次
发布时间:2019-03-25

本文共 5302 字,大约阅读时间需要 17 分钟。

Java IO流入门与进阶

在Java编程中,输入输出操作是开发中不可或缺的一部分。了解IO流的工作原理和使用方法,能够帮助我们高效地处理文件操作和数据传输。Java中提供了丰富的IO流类型,每种流都有其独特的功能和应用场景。本文将从缓冲流、转换流、标准输入输出流、对象流以及随机存取流四个方面,详细介绍Java IO流的核心知识。


一、缓冲流

缓冲流是一种重要的IO流类型,能够显著提高数据读写速度。传统的文件操作主要通过硬盘进行,读写速度较慢。而缓冲流会将数据暂存到内存中,通过内存操作代替硬盘操作,大约能提升75000倍的性能。

1. 缓冲字节流

  • BufferedInputStream:用于读取文件。
public static void BufferedInputStream(String inpath) {    try {        BufferedInputStream br = new BufferedInputStream(new FileInputStream(inpath));        byte[] bytes = new byte[1024];        int len = 0;        while ((len = br.read(bytes)) != -1) {            System.out.println(new String(bytes, 0, len));        }        br.close();    } catch (Exception e) {        e.printStackTrace();    }}
  • BufferedOutputStream:用于写入文件。
public static void BufferedOutputStream(String text, String outpath) {    try {        BufferedOutputStream bf = new BufferedOutputStream(new FileOutputStream(outpath));        byte[] bytes = text.getBytes();        bf.write(bytes);        bf.flush();        bf.close();    } catch (Exception e) {        e.printStackTrace();    }}

缓冲流的主要优势在于减少IO操作的频率,提高读写效率。

2. 缓冲字符流

字符流和字节流在处理文本文件时有明显区别。字符流(BufferedReader和BufferedWriter)能够自动将字符转换为Unicode码点,适用于中文文件,提高处理效率。

public static void BufferedReader(String inpath) {    try {        BufferedReader bfr = new BufferedReader(new FileReader(inpath));        char[] chars = new char[1024];        int len = 0;        while ((len = bfr.read(chars)) != -1) {            System.out.println(new String(chars, 0, len));        }        bfr.close();    } catch (Exception e) {        e.printStackTrace();    }}
public static void BufferedWriter(String text, String outpath) {    try {        BufferedWriter bfw = new BufferedWriter(new FileWriter(outpath));        bfw.write(text);        bfw.flush();        bfw.close();    } catch (Exception e) {        e.printStackTrace();    }}

二、转换流

文件的编码格式影响着读写的兼容性。常见编码格式包括ISO-8856-1(适合英文文件)、GBK和UTF-8(适合中文文件)。转换流(InputStreamReader和OutputStreamWriter)能够将字节流转换为字符流,确保读写一致性。

public static void InputStreamReader(String inpath) {    try {        InputStreamReader isr = new InputStreamReader(new FileInputStream(inpath), "UTF-8");        char[] chars = new char[1024];        int len = 0;        while ((len = isr.read(chars)) != -1) {            System.out.println(new String(chars, 0, len));        }        isr.close();    } catch (Exception e) {        e.printStackTrace();    }}
public static void OutputStreamWriter(String text, String outpath) {    try {        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(outpath), "UTF-8");        osw.write(text);        osw.flush();        osw.close();    } catch (Exception e) {        e.printStackTrace();    }}

三、标准输入输出流

标准输入输出流(System.in和System.out)是Java程序与外部输入输出通信的通道。通过缓冲流加速,可以提高输入输出效率。

public static void SystemIn() throws Exception {    try {        InputStreamReader isr = new InputStreamReader(System.in);        BufferedReader br = new BufferedReader(isr);        String str = "";        while ((str = br.readLine()) != null) {            System.out.println(str);        }        br.close();    } catch (Exception e) {        e.printStackTrace();    }}
public static void SystemToFiles() throws Exception {    try {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\demo\\demo.txt"));        String str = "";        while ((str = br.readLine()) != null) {            if (str.equals("over")) break;            bw.write(str);        }        bw.flush();        bw.close();    } catch (Exception e) {        e.printStackTrace();    }}

四、对象流(重点)

对象流(ObjectInputStream和ObjectOutputStream)用于将Java对象序列化并持久化存储。序列化是将对象的属性转化为二进制流,反序列化则是恢复为原始对象。

public static void serialize(String outpath) throws Exception {    try {        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(outpath));        Person p = new Person();        p.name = "张三";        p.age = 23;        out.writeObject(p);        out.flush();        out.close();    } catch (Exception e) {        e.printStackTrace();    }}
public static void deserialize(String input) throws Exception {    try {        ObjectInputStream in = new ObjectInputStream(new FileInputStream(input));        Object o = in.readObject();        Person p = (Person) o;        System.out.println(p.name + "---------" + p.age);        in.close();    } catch (Exception e) {        e.printStackTrace();    }}

五、随机存取流

随机存取流(RandomAccessFile)允许程序随机读写文件内容。常见于处理大文件或特定文件部分数据。

public static void RandomAccessFileRead() throws Exception {    try {        RandomAccessFile ra = new RandomAccessFile("D:\\demo\\demo1.txt", "r");        ra.seek(8); // 定位读取位置        byte[] bytes = new byte[1024];        int len = 0;        while ((len = ra.read(bytes)) != -1) {            System.out.println(new String(bytes, 0, len));        }        ra.close();    } catch (Exception e) {        e.printStackTrace();    }}
public static void RandomAccessFileWrite() throws Exception {    try {        RandomAccessFile ra = new RandomAccessFile("D:\\demo\\demo1.txt", "rw");        ra.seek(ra.length());        ra.write("你好".getBytes());        ra.close();    } catch (Exception e) {        e.printStackTrace();    }}

通过以上介绍,Java程序mer能够更好地掌握IO流的使用方法,实现高效的文件操作和数据处理任务。同时,理解IO流的原理有助于优化程序性能,提升代码执行效率。

转载地址:http://pbzyk.baihongyu.com/

你可能感兴趣的文章
localhost:5000在MacOS V12(蒙特利)中不可用
查看>>
mac mysql 进程_Mac平台下启动MySQL到完全终止MySQL----终端八步走
查看>>
Mac OS 12.0.1 如何安装柯美287打印机驱动,刷卡打印
查看>>
MangoDB4.0版本的安装与配置
查看>>
Manjaro 24.1 “Xahea” 发布!具有 KDE Plasma 6.1.5、GNOME 46 和最新的内核增强功能
查看>>
mapping文件目录生成修改
查看>>
MapReduce程序依赖的jar包
查看>>
mariadb multi-source replication(mariadb多主复制)
查看>>
MariaDB的简单使用
查看>>
MaterialForm对tab页进行隐藏
查看>>
Member var and Static var.
查看>>
memcached高速缓存学习笔记001---memcached介绍和安装以及基本使用
查看>>
memcached高速缓存学习笔记003---利用JAVA程序操作memcached crud操作
查看>>
Memcached:Node.js 高性能缓存解决方案
查看>>
memcache、redis原理对比
查看>>
memset初始化高维数组为-1/0
查看>>
Metasploit CGI网关接口渗透测试实战
查看>>
Metasploit Web服务器渗透测试实战
查看>>
Moment.js常见用法总结
查看>>
MongoDB出现Error parsing command line: unrecognised option ‘--fork‘ 的解决方法
查看>>