概念
JAVA IO(Input/Output)是Java编程语言中用于读取和写入数据的API。它允许程序读取和写入文件、网络连接等I/O流,在Java中使用IO时必须使用java.io包和相关类。
Java I/O提供了以下三种类型的流:
-
字节流(byte stream):用于读取和写入8位字节。
-
字符流(character stream):用于读取和写入16位字符。
-
缓冲流(buffered stream):提供了一种可以再JAVA IO基础上进行互动式输入/输出的通道。
在Java IO中,输入和输出流是分开的。输入流是用来从文件或其他设备中读取数据的流;输出流是用来将数据写入文件或其他设备的流。因为数据的处理都是以流的形式进行的,所以Java IO又叫做“流IO”。
Java IO提供了很多用于读写数据的类和方法,比如FileInputStream、FileOutputStream、ByteArrayInputStream、ByteArrayOutputStream、DataInputStream、DataOutputStream等等。开发人员可以根据自己的需求,选择相应的流和类来进行数据的输入和输出。
- 字节流输入输出
字节流是用来读取和写入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();
- 字符流输入输出
字符流用于读取和写入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();
- 缓冲流
缓冲流提供了更高效的读写功能。
// 使用 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();
- 对象流
对象流提供了读写对象的方法,可以将一个对象完整地保存到文件或网络中。
// 使用 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类和方法。