下面我将用代码演示Java中IO流的基本使用方法。
使用FileInputStream读取文件中的字节数据:
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamExample {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("example.txt");
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data);
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出结果是将example.txt文件中的内容输出到控制台上,例如:
Hello, world!
This is an example file.
解释一下以上代码的的意思:
我们首先创建了一个FileInputStream对象,并打开了名为example.txt的文件(这里具体写你对应的路径)。然后,我们使用read()方法读取文件中的字节数据,然后再将其转换为字符输出到控制台。最后,我们关闭了输入流对象。这是整个流程。
使用BufferedReader和FileWriter读取和写入文本文件的例子:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
FileWriter fw = new FileWriter("output.txt");
String line;
while ((line = br.readLine()) != null) {
fw.write(line);
fw.write("\n");
}
br.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出结果是将input.txt文件中的内容逐行写入到output.txt文件中,例如:
input.txt文件内容:
This is the first line.
This is the second line.
This is the third line.
output.txt文件内容:
This is the first line.
This is the second line.
This is the third line.
解释一下以上代码的的意思:
在上面的代码中,我们创建了一个BufferedReader对象和一个FileWriter对象,并打开了名为input.txt的文件和名为output.txt的文件。然后,我们使用readLine()方法逐行读取文件中的字符数据,并将其写入到输出文件中。最后,我们关闭了输入流对象和输出流对象。
总结一下:这些例子只是Java中IO流的基本用法,Java的IO流类库还提供了更多的功能和选项,可以根据具体需求进行选择和使用。