Java中IO流处理常用的函数示例
发布时间:2023-06-30 12:23:47
在Java中,常用的IO流处理函数包括文件的读写、字符的读写和字节的读写等。下面是一些常见的函数示例:
1. 文件的读取和写入
使用FileInputStream和FileOutputStream可以读取和写入文件。
示例:
// 读取文件
try (FileInputStream fis = new FileInputStream("input.txt")) {
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
// 写入文件
try (FileOutputStream fos = new FileOutputStream("output.txt")) {
String text = "Hello, World!";
fos.write(text.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
2. 字符的读取和写入
使用FileReader和FileWriter可以读取和写入字符流。
示例:
// 读取字符
try (FileReader reader = new FileReader("input.txt")) {
int data;
while ((data = reader.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
// 写入字符
try (FileWriter writer = new FileWriter("output.txt")) {
String text = "Hello, World!";
writer.write(text);
} catch (IOException e) {
e.printStackTrace();
}
3. 字节的读取和写入
使用BufferedInputStream和BufferedOutputStream可以读取和写入字节流。
示例:
// 读取字节
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("input.txt"))) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
System.out.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
// 写入字节
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("output.txt"))) {
String text = "Hello, World!";
bos.write(text.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
这些是Java中常用的IO流处理函数示例。通过使用这些函数,我们可以方便地读取和写入文件、字符和字节。注意在使用IO流时,需要适时地关闭或释放资源,以避免内存泄漏和资源浪费。
