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

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

文章目录


缓冲流

转换流

标准输入输出流

打印流

数据流

对象流

随机存取文件流

Java NIO


缓冲流


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


43ece2842ef842e5a1f61dc305747ad5.png


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

BufferedInputStream 和 BufferedOutputStream

BufferedReader 和 BufferedWriter


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


向流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区写满,

BufferedOutputStream才会把缓冲区中的数据一次性写到文件里。使用方法

flush()可以强制将缓冲区的内容全部写入输出流。


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

会相应关闭内层节点流。


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


7d996732402849bc9525d9dcbc5ee213.png


以字节流BufferedInputStream 和 BufferedOutputStream示例具体操作:


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(字节转为字符输出)


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


9b013296ece54502afcd277c90580e94.png


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.in和System.out分别代表了系统标准的输入和输出设备

默认输入设备是:键盘,输出设备是:显示器(控制台)


System.in的类型是InputStream

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


重定向:通过System类的setIn(),setOut()方法对默认设备进行改变:

public static void setIn(InputStream in)

public static void setOut(PrintStream out)


5a7f0c5110544c1f9c7104d06b490d96.png


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();
            }
        }
    }
}


打印流


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


打印流:PrintStream和PrintWriter

提供了一系列重载的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类的数据)

DataInputStream 和 DataOutputStream

分别“套接”在 InputStream 和 OutputStream 子类的流上。


5a5573e59a044059aea288118fcada1b.png


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();
            }
        }
    }
}


对象流


ObjectInputStream和OjbectOutputSteam


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


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

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


ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量。


实现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;
    }
    @Override
    public 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;
    }
    @Override
    public 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类。并且它实现了DataInput、DataOutput这两个接口,也就意味着这个类既可以读也可以写。


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 的访问模式:


28b30f54f5a44ce0a3e0bdad4089748c.png


如果模式为只读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。


bf4e4e301a28425489b7cc305434699e.png


随着 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路径


ba11c647b8794ff5820442b2ee8b39e1.pngcbc20cfdb2e846e2926909caa4b0de0d.png3857d6ea2b284ad2b48c3e3c498c1c9d.png





相关文章
|
Java API 开发工具
【Azure Developer】Java代码实现获取Azure 资源的指标数据却报错 "invalid time interval input"
在使用 Java 调用虚拟机 API 获取指标数据时,因本地时区设置非 UTC,导致时间格式解析错误。解决方法是在代码中手动指定时区为 UTC,使用 `ZoneOffset.ofHours(0)` 并结合 `withOffsetSameInstant` 方法进行时区转换,从而避免因时区差异引发的时间格式问题。
540 4
|
算法 Java
Java多线程编程:实现线程间数据共享机制
以上就是Java中几种主要处理多线程序列化资源以及协调各自独立运行但需相互配合以完成任务threads 的技术手段与策略。正确应用上述技术将大大增强你程序稳定性与效率同时也降低bug出现率因此深刻理解每项技术背后理论至关重要.
817 16
|
数据采集 JSON Java
Java爬虫获取1688店铺所有商品接口数据实战指南
本文介绍如何使用Java爬虫技术高效获取1688店铺商品信息,涵盖环境搭建、API调用、签名生成及数据抓取全流程,并附完整代码示例,助力市场分析与选品决策。
|
数据采集 存储 前端开发
Java爬虫性能优化:多线程抓取JSP动态数据实践
Java爬虫性能优化:多线程抓取JSP动态数据实践
|
传感器 分布式计算 安全
Java 大视界 -- Java 大数据在智能安防入侵检测系统中的多源数据融合与分析技术(171)
本文围绕 Java 大数据在智能安防入侵检测系统中的应用展开,剖析系统现状与挑战,阐释多源数据融合及分析技术,结合案例与代码给出实操方案,提升入侵检测效能。
|
自然语言处理 Java 关系型数据库
Java|小数据量场景的模糊搜索体验优化
在小数据量场景下,如何优化模糊搜索体验?本文分享一个简单实用的方案,虽然有点“土”,但效果还不错。
477 0
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
Java API 数据处理
深潜数据海洋:Java文件读写全面解析与实战指南
通过本文的详细解析与实战示例,您可以系统地掌握Java中各种文件读写操作,从基本的读写到高效的NIO操作,再到文件复制、移动和删除。希望这些内容能够帮助您在实际项目中处理文件数据,提高开发效率和代码质量。
1158 4
|
数据采集 JSON Java
Java爬虫获取微店快递费用item_fee API接口数据实现
本文介绍如何使用Java开发爬虫程序,通过微店API接口获取商品快递费用(item_fee)数据。主要内容包括:微店API接口的使用方法、Java爬虫技术背景、需求分析和技术选型。具体实现步骤为:发送HTTP请求获取数据、解析JSON格式的响应并提取快递费用信息,最后将结果存储到本地文件中。文中还提供了完整的代码示例,并提醒开发者注意授权令牌、接口频率限制及数据合法性等问题。
|
存储 NoSQL Java
使用Java和Spring Data构建数据访问层
本文介绍了如何使用 Java 和 Spring Data 构建数据访问层的完整过程。通过创建实体类、存储库接口、服务类和控制器类,实现了对数据库的基本操作。这种方法不仅简化了数据访问层的开发,还提高了代码的可维护性和可读性。通过合理使用 Spring Data 提供的功能,可以大幅提升开发效率。
583 21