JAVA IO

概念

JAVA IO(Input/Output)是Java编程语言中用于读取和写入数据的API。它允许程序读取和写入文件、网络连接等I/O流,在Java中使用IO时必须使用java.io包和相关类。

Java I/O提供了以下三种类型的流:

  1. 字节流(byte stream):用于读取和写入8位字节。

  2. 字符流(character stream):用于读取和写入16位字符。

  3. 缓冲流(buffered stream):提供了一种可以再JAVA IO基础上进行互动式输入/输出的通道。

在Java IO中,输入和输出流是分开的。输入流是用来从文件或其他设备中读取数据的流;输出流是用来将数据写入文件或其他设备的流。因为数据的处理都是以流的形式进行的,所以Java IO又叫做“流IO”。

Java IO提供了很多用于读写数据的类和方法,比如FileInputStream、FileOutputStream、ByteArrayInputStream、ByteArrayOutputStream、DataInputStream、DataOutputStream等等。开发人员可以根据自己的需求,选择相应的流和类来进行数据的输入和输出。

  1. 字节流输入输出

字节流是用来读取和写入8位字节的流。Byte数组是使用字节流的基本类型。

// 使用 FileInputStream 读取文件
FileInputStream fis = new FileInputStream("input.txt");
// 读取数据
int data = fis.read();
while (data != -1) {
    // 处理读取到的数据
    System.out.print((char) data);
    data = fis.read();
}
// 关闭流
fis.close();

// 使用 FileOutputStream 写入文件
FileOutputStream fos = new FileOutputStream("output.txt");
String data = "Hello World";
fos.write(data.getBytes());
fos.flush();
// 关闭流
fos.close();

 

  1. 字符流输入输出

字符流用于读取和写入16位字符,可以使用字符数组。

// 使用 FileReader 读取文件
FileReader fr = new FileReader("input.txt");
char[] buffer = new char[1024];
// 读取数据
int length = fr.read(buffer);
while (length != -1) {
    // 处理读取到的数据
    System.out.print(new String(buffer, 0, length));
    length = fr.read(buffer);
}
// 关闭流
fr.close();

// 使用 FileWriter 写入文件
FileWriter fw = new FileWriter("output.txt");
String data = "Hello World";
fw.write(data.toCharArray());
fw.flush();
// 关闭流
fw.close();

  1. 缓冲流

缓冲流提供了更高效的读写功能。

// 使用 BufferedInputStream 读取文件
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("input.txt"));
// 读取数据
byte[] buffer = new byte[1024];
int length = bis.read(buffer);
while (length != -1) {
    // 处理读取到的数据
    System.out.print(new String(buffer, 0, length));
    length = bis.read(buffer);
}
// 关闭流
bis.close();

// 使用 BufferedOutputStream 写入文件
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("output.txt"));
String data = "Hello World";
bos.write(data.getBytes());
bos.flush();
// 关闭流
bos.close();

  1. 对象流

对象流提供了读写对象的方法,可以将一个对象完整地保存到文件或网络中。

// 使用 ObjectOutputStream 写入对象
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.ser"));
Message message = new Message("Hello World", new Date());
oos.writeObject(message);
oos.flush();
// 关闭流
oos.close();

// 使用 ObjectInputStream 读取对象
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.ser"));
Message message = (Message) ois.readObject();
// 处理读取到的对象
System.out.println(message);
// 关闭流
ois.close();

这是一个简单的Java IO教程,介绍了一些常用的Java IO类和方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值