Java中的IO函数,实现文件读写操作
Java 中的 Input/Output(IO)代码可以让应用程序与计算机的外部环境打交道,例如读取或写入文件、访问数据库、使用网络和操作图形用户界面(GUI)。本文将介绍 Java 中的 IO 函数以及如何实现文件读写操作。
Java 提供了两个 IO 体系结构:流式 IO 和基于 NIO 的通道 IO。
一、流式 IO
Java 中的流式 IO 是指以数据流的形式读写数据。这种 IO 应用于中小规模数据读写操作,优点在于数据可以逐步读取或写入,节省系统内存。
1. 文件读取
Java 中可以使用 FileInputStream 类读取文件。例如,以下代码可以读取一个文件并将其存储到 byte 数组中:
import java.io.*;
public class FileInputStreamExample {
public static void main(String[] args) {
try {
FileInputStream in = new FileInputStream("file.txt");
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = in.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, bytesRead));
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 文件写入
Java 中可以使用 FileOutputStream 类将数据写入文件。例如,以下代码将字符串写入文件:
import java.io.*;
public class FileOutputStreamExample {
public static void main(String[] args) {
try {
String data = "Java is cool!";
FileOutputStream out = new FileOutputStream("file.txt");
out.write(data.getBytes());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
二、基于 NIO 的通道 IO
Java 的 NIO(New IO)库提供了非阻塞式 IO,它以通道为核心,而流式 IO 则以流为核心。对于大规模数据读写操作,使用非阻塞式 IO 会更加高效。
1. 文件读取
Java 中可以使用 BufferedReader 和 ByteBuffer 来读取文件。以下代码展示了如何使用 ByteBuffer 从文件中读取数据:
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class FileChannelExample {
public static void main(String[] args) {
try {
RandomAccessFile file = new RandomAccessFile("file.txt", "r");
FileChannel channel = file.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead = channel.read(buffer);
while (bytesRead != -1) {
System.out.println(new String(buffer.array(), 0, bytesRead));
buffer.clear();
bytesRead = channel.read(buffer);
}
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 文件写入
Java 中可以使用 BufferedWriter 和 ByteBuffer 来写入文件。以下代码展示了如何使用 ByteBuffer 向文件中写入数据:
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class FileChannelExample {
public static void main(String[] args) {
try {
RandomAccessFile file = new RandomAccessFile("file.txt", "rw");
FileChannel channel = file.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
String data = "Java is cool!";
buffer.put(data.getBytes());
buffer.flip();
channel.write(buffer);
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
总结
Java 中提供了流式 IO 和基于 NIO 的通道 IO 两种读写文件的方法。流式 IO 适用于中小规模数据读写操作,可逐步读取或写入数据,节省系统内存。基于 NIO 的通道 IO 适用于大规模数据读写操作,速度更快,但较为复杂。以上代码仅为演示用途,实际使用时需考虑读写的文件大小、读写速度等因素。
