用代码用例说明Java中IO流的使用
时间: 2024-05-08 17:15:56 浏览: 16
1. 文件读取
```java
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
public class FileReaderExample {
public static void main(String[] args) {
try {
File file = new File("myfile.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
2. 文件写入
```java
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
public class FileWriterExample {
public static void main(String[] args) {
try {
File file = new File("myfile.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("Hello, World!");
bufferedWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
3. 字节流读取
```java
import java.io.File;
import java.io.FileInputStream;
public class FileInputStreamExample {
public static void main(String[] args) {
try {
File file = new File("myfile.txt");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
fileInputStream.close();
String content = new String(data, "UTF-8");
System.out.println(content);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
4. 字节流写入
```java
import java.io.File;
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String[] args) {
try {
File file = new File("myfile.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte[] data = "Hello, World!".getBytes("UTF-8");
fileOutputStream.write(data);
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)