Java文件输入输出流各种类的代码
时间: 2024-02-20 10:56:58 浏览: 63
实验9 Java输入输出流.doc
5星 · 资源好评率100%
以下是Java文件输入输出流各种类的代码示例:
1. FileInputStream和FileOutputStream
读取文件内容并写入文件:
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
try {
FileInputStream input = new FileInputStream("input.txt");
FileOutputStream output = new FileOutputStream("output.txt");
int data;
while ((data = input.read()) != -1) {
output.write(data);
}
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. FileReader和FileWriter
读取文本文件内容并写入文本文件:
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("input.txt");
FileWriter writer = new FileWriter("output.txt");
int data;
while ((data = reader.read()) != -1) {
writer.write(data);
}
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
3. BufferedInputStream和BufferedOutputStream
使用缓冲区读取文件内容并写入文件:
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
try {
FileInputStream input = new FileInputStream("input.txt");
FileOutputStream output = new FileOutputStream("output.txt");
BufferedInputStream bufferedInput = new BufferedInputStream(input);
BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
int data;
while ((data = bufferedInput.read()) != -1) {
bufferedOutput.write(data);
}
bufferedInput.close();
bufferedOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
4. BufferedReader和BufferedWriter
使用缓冲区读取文本文件内容并写入文本文件:
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("input.txt");
FileWriter writer = new FileWriter("output.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
BufferedWriter bufferedWriter = new BufferedWriter(writer);
String line;
while ((line = bufferedReader.readLine()) != null) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文