java io流读写文件
时间: 2023-11-18 21:54:49 浏览: 51
Java IO流是Java中用于读写文件和其他输入/输出操作的机制。Java IO流提供了两种类型的流:字节流和字符流。字节流用于读写二进制数据,而字符流用于读写文本数据。Java IO流提供了许多类和方法来读写文件,包括FileInputStream、FileOutputStream、BufferedReader、BufferedWriter等。下面是Java IO流读写文件的基本步骤:
1.创建一个File对象,该对象表示要读写的文件。
2.创建一个输入流或输出流对象,该对象将与文件关联。
3.使用输入流或输出流对象读取或写入文件。
4.关闭输入流或输出流对象,以释放资源。
下面是两个用Java IO流读写文件的例子:
1.使用字节流读写文件:
```
File file = new File("example.txt");
FileOutputStream fos = new FileOutputStream(file);
String str = "Hello, world!";
byte[] bytes = str.getBytes();
fos.write(bytes);
fos.close();
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = fis.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, length));
}
fis.close();
```
2.使用字符流读写文件:
```
File file = new File("example.txt");
FileWriter fw = new FileWriter(file);
fw.write("Hello, world!");
fw.close();
FileReader fr = new FileReader(file);
char[] buffer = new char[1024];
int length = 0;
while ((length = fr.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, length));
}
fr.close();
```