博客
关于我
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/

你可能感兴趣的文章
MongoDB出现Error parsing command line: unrecognised option ‘--fork‘ 的解决方法
查看>>
mxGraph改变图形大小重置overlay位置
查看>>
MongoDB学习笔记(8)--索引及优化索引
查看>>
MQTT工作笔记0009---订阅主题和订阅确认
查看>>
ms sql server 2008 sp2更新异常
查看>>
MS UC 2013-0-Prepare Tool
查看>>
msbuild发布web应用程序
查看>>
MSB与LSB
查看>>
MSCRM调用外部JS文件
查看>>
MSCRM调用外部JS文件
查看>>
MSEdgeDriver (Chromium) 不适用于版本 >= 79.0.313 (Canary)
查看>>
MsEdgeTTS开源项目使用教程
查看>>
msf
查看>>
MSSQL数据库查询优化(一)
查看>>
MSSQL日期格式转换函数(使用CONVERT)
查看>>
MSTP多生成树协议(第二课)
查看>>
MSTP是什么?有哪些专有名词?
查看>>
Mstsc 远程桌面链接 And 网络映射
查看>>
Myeclipse常用快捷键
查看>>
MyEclipse用(JDBC)连接SQL出现的问题~
查看>>