21xrx.com
2024-09-17 04:14:21 Tuesday
登录
文章检索 我的文章 写文章
深入了解Java中的IO流:包含哪些种类及其应用
2023-06-13 14:23:09 深夜i     --     --
Java IO流 字节流 字符流 缓冲流 对象流

Java中的IO流是进行文件、网络通信等输入输出操作的重要手段。它可以根据不同的应用场景,分为多种不同类型,包括字节流、字符流、缓冲流、对象流等。在本文中,我们将深入了解Java中常见的IO流的种类,并讲解其应用及实现代码案例。

一、字节流(InputStream 和 OutputStream)

字节流是Java I/O流中最基本的类型,它可以对字节数据进行读写操作。其中,InputStream用于读取字节数据,OutputStream用于写入字节数据。以下是利用字节流进行读写操作的代码:


//读取文件内容, path为文件路径

FileInputStream input = new FileInputStream(path);

int data = input.read();

while(data != -1) {

  System.out.print((char) data);

  data = input.read();

}

input.close();

//写入文件内容,并保存为OutExample.txt, path为文件路径

FileOutputStream output = new FileOutputStream(path);

String str = "Hello, world!";

byte[] data = str.getBytes();

output.write(data);

output.close();

二、字符流(Reader 和 Writer)

字符流是Java中处理字符数据的一种流,其特点是输入和输出的是16位unicode编码的字符。其中,Reader用于读取字符数据,Writer用于写入字符数据。以下是利用字符流进行读写操作的代码:


//读取文件内容, path为文件路径

FileReader reader = new FileReader(path);

int data = reader.read();

while(data != -1) {

  System.out.print((char) data);

  data = reader.read();

}

reader.close();

//写入文件内容,并保存为OutExample.txt, path为文件路径

FileWriter writer = new FileWriter(path);

String str = "Hello, world!";

writer.write(str);

writer.close();

三、缓冲流(BufferedInputStream 和 BufferedOutputStream)

缓冲流是为了提高字节流和字符流的读写速度而设计的。它通过设置缓冲区来减少与磁盘的交互次数,从而提供效率。以下是利用缓冲流进行读写操作的代码:


//读取文件内容, path为文件路径

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));

int data = bis.read();

while(data != -1) {

  System.out.print((char) data);

  data = bis.read();

}

bis.close();

//写入文件内容,并保存为OutExample.txt, path为文件路径

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));

String str = "Hello, world!";

byte[] data = str.getBytes();

bos.write(data);

bos.flush();

bos.close();

四、对象流(ObjectInputStream 和 ObjectOutputStream)

对象流是Java中序列化和反序列化对象的一种流,它可以将对象以二进制流的形式进行读写操作。以下是利用对象流进行读写操作的代码:


//写入对象并保存为Example.txt, path为文件路径

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));

oos.writeObject(new Person("Tom", 20));

oos.flush();

oos.close();

//读取对象, path为文件路径

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));

Person person = (Person) ois.readObject();

System.out.println(person.getName() + " " + person.getAge());

ois.close();

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复