深入解析Java中的IO流操作:具体场景示例
在Java中,IO流(Input/Output Streams)是用于处理输入和输出的抽象。以下是一些具体的场景示例:
文件读写:
- 从文件读取数据:
File file = new File("filename.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// 处理读取的行
System.out.println(line);
}
br.close();
- 将数据写入文件:
String dataToWrite = "Hello, World!";
File file = new File("filename.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(dataToWrite);
bw.newLine(); // 添加新行
bw.close();
- 从文件读取数据:
网络流:
- 发送HTTP请求获取数据:
URL url = new URL("http://example.com/api/data");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
// 获取响应内容并处理数据
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))));
String line;
while ((line = br.readLine()) != null)) {
System.out.println(line);
}
br.close();
} else {
System.out.println("Error: HTTP request failed with code " + responseCode);
}
conn.disconnect();
- 发送HTTP请求获取数据:
字节流:
使用ByteBuffer处理大量数据(如网络响应):
ByteBuffer byteBuffer = ByteBuffer.allocate(1024); // 创建一个1KB的缓冲区
// 从网络等地方填充缓冲区
byteBuffer.put((byte) 'H')); byteBuffer.put((byte) 'e')); byteBuffer.put((byte) 'l')); byteBuffer.put((byte) 'o')); // 用实际数据替换以下内容
byteBuffer.flip(); // 转置缓冲区的头部,使其位于缓冲区的尾部
// 从缓冲区中读取数据
String readData = new String(byteBuffer.array()));
System.out.println(readData);
byteBuffer.clear(); // 清空缓冲区
以上示例涵盖了Java中IO流操作的各种场景,包括文件处理、网络通信和字节操作等。
还没有评论,来说两句吧...