Java中的IO操作:文件读写、输入输出流实例
在Java中,IO(Input/Output)操作主要包括文件的读写以及使用各种输入输出流。以下是一些关键的概念和实例:
文件读写:
- 使用
FileInputStream
或ObjectInputStream
从文件读取数据。 - 使用
FileOutputStream
或ObjectOutputStream
将数据写入文件。
- 使用
输入输出流:
InputStreamReader
和StringWriter
: 这两个组合可以实现字符串与字符流之间的转换。BufferedReader
和BufferedWriter
: 这些类提供了对输入/输出流的缓冲,提高了性能。
使用Java IO操作的示例代码:
import java.io.*;
public class IOExample {
public static void main(String[] args) {
// 文件读写示例
String filePath = "example.txt"; // 文件路径
try (FileWriter writer = new FileWriter(filePath)) {
writer.write("Hello, World!");
} catch (IOException e) {
System.out.println("Error occurred while writing to file: " + e.getMessage());
}
// 流读写示例
String content = "Java IO operations example";
try (PrintWriter writer = new PrintWriter(new File("example2.txt")))) {
writer.print(content);
} catch (IOException e) {
System.out.println("Error occurred while writing to file: " + e.getMessage());
}
// 使用缓冲流
String input = "Java IO operations example";
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)), 1024)); { // 设置缓冲区大小
String line;
while ((line = reader.readLine()) != null)) {
System.out.println("Input: " + line);
// 这里可以对输入进行处理,例如替换某些字符等
line = input.replace(line, "Processed " + line)); // 对输入进行预处理,这里简单替换了原内容
System.out.println("Output: " + line); // 输出预处理后的结果
}
reader.close();
} catch (IOException e) {
System.out.println("Error occurred while working with input/output streams: " + e.getMessage());
}
}
这个示例代码展示了如何使用Java的文件读写功能以及输入输出流来实现各种IO操作。
还没有评论,来说两句吧...