// Java字节流和字符流示例代码
import java.io.*;
public class StreamExample {
// 字节流示例:使用FileInputStream和FileOutputStream读写字节数据
public static void byteStreamExample() {
String filePath = "example.txt";
byte[] data = "Hello, World!".getBytes();
try (FileOutputStream fos = new FileOutputStream(filePath)) {
// 写入字节数据到文件
fos.write(data);
System.out.println("字节数据已写入文件");
} catch (IOException e) {
e.printStackTrace();
}
try (FileInputStream fis = new FileInputStream(filePath)) {
// 从文件中读取字节数据
byte[] readData = new byte[fis.available()];
fis.read(readData);
System.out.println("从文件中读取的字节数据: " + new String(readData));
} catch (IOException e) {
e.printStackTrace();
}
}
// 字符流示例:使用FileReader和FileWriter读写字符数据
public static void charStreamExample() {
String filePath = "example_char.txt";
String content = "你好,世界!";
try (FileWriter fw = new FileWriter(filePath)) {
// 写入字符数据到文件
fw.write(content);
System.out.println("字符数据已写入文件");
} catch (IOException e) {
e.printStackTrace();
}
try (FileReader fr = new FileReader(filePath)) {
// 从文件中读取字符数据
char[] readData = new char[fr.available()];
fr.read(readData);
System.out.println("从文件中读取的字符数据: " + new String(readData));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
byteStreamExample();
charStreamExample();
}
}
字节流(Byte Stream):
FileInputStream和FileOutputStream来读写字节数据。FileOutputStream用于将字节数据写入文件。FileInputStream用于从文件中读取字节数据。字符流(Character Stream):
FileReader和FileWriter来读写字符数据。FileWriter用于将字符数据写入文件。FileReader用于从文件中读取字符数据。自动资源管理(try-with-resources):
try-with-resources语句可以确保流在使用完毕后自动关闭,避免资源泄漏。异常处理:
try-catch块捕获并处理可能发生的IOException,以确保程序的健壮性。上一篇:java创建二维数组
下一篇:java转义字符对照表
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站