0
点赞
收藏
分享

微信扫一扫

java 输出输入流

Java 输入输出流的实现

流程概述

在Java中,要实现输入输出流可以分为以下几个步骤:

  1. 打开输入输出流
  2. 读取或写入数据
  3. 关闭输入输出流

下面将详细介绍每个步骤的具体操作。

1. 打开输入输出流

要使用Java的输入输出流,需要先创建一个对应的输入输出流对象。可以根据需求选择使用字节流或字符流,其中字节流适用于处理二进制数据,而字符流适用于处理文本数据。

打开输入流

使用字节流读取文件内容的示例代码如下:

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamExample {

public static void main(String[] args) {
InputStream input = null;

try {
// 创建文件输入流
input = new FileInputStream(input.txt);

// 读取数据
int data = input.read();
while (data != -1) {
// 处理数据

// 继续读取下一个字节
data = input.read();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭输入流
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

上述代码示例中,首先创建了一个 FileInputStream 对象,并传入要读取的文件名作为参数。然后使用 read() 方法读取文件的字节数据,直到读取到文件末尾(返回值为 -1)。在循环中可以对读取到的数据进行处理。最后,通过 close() 方法关闭输入流。

打开输出流

使用字节流写入文件内容的示例代码如下:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class OutputStreamExample {

public static void main(String[] args) {
OutputStream output = null;

try {
// 创建文件输出流
output = new FileOutputStream(output.txt);

// 写入数据
byte[] data = Hello, world!.getBytes();
output.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭输出流
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

上述代码示例中,首先创建了一个 FileOutputStream 对象,并传入要写入的文件名作为参数。然后使用 write() 方法将字节数据写入文件。最后,通过 close() 方法关闭输出流。

2. 读取或写入数据

在打开输入输出流后,可以通过相应的方法读取或写入数据。

读取数据

使用字符流读取文件内容的示例代码如下:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample {

public static void main(String[] args) {
BufferedReader reader = null;

try {
// 创建文件读取流
reader = new BufferedReader(new FileReader(input.txt));

// 读取数据
String line = reader.readLine();
while (line != null) {
// 处理数据

// 继续读取下一行
line = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭读取流
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

上述代码示例中,首先创建了一个 BufferedReader 对象,并将其包装在 FileReader 中。然后使用 readLine() 方法逐行读取文件内容,直到读取到文件末尾(返回值为 null)。在循环中可以对读取到的数据进行处理。最后,通过 close() 方法关闭读取流。

写入数据

使用字符流写入文件内容的示例代码如下:

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterExample {

public static void main(String[] args) {
BufferedWriter writer = null;

try {
// 创建文件写入流
writer = new BufferedWriter(new FileWriter(output.txt));

// 写入数据
writer.write(Hello, world!);
} catch (IOException e) {
e.printStackTrace();
} finally
举报

相关推荐

0 条评论