Java中的IO流:文件读写操作实例
在Java中,IO(Input/Output)流用于处理各种类型的输入和输出操作,包括文件读写。以下是一些典型的文件读写操作实例:
- 文件的创建:
```java
File file = new File(“myfile.txt”); // 创建一个表示文件的新File对象
// 如果文件不存在,则尝试创建它
if (!file.exists()) {
boolean created = file.createNewFile(); // 使用createNewFile方法创建新文件
if (created) { // 如果成功创建文件,打印提示信息
System.out.println(“File created successfully: “ + file.getAbsolutePath());
}
} else { // 如果文件已经存在,直接读取或写入
System.out.println(“File already exists: “ + file.getAbsolutePath());
}
}
2. **文件的读取**:
```java
try (BufferedReader br = new BufferedReader(new FileReader(file)))) {
String line;
while ((line = br.readLine()) != null) { // 逐行读取
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
e.printStackTrace();
}
- 文件的写入:
try (PrintWriter writer = new PrintWriter(new FileWriter(file)))) {
writer.print("Hello, World!\n"); // 写入内容
} catch (IOException e) {
System.err.println("Error writing file: " + e.getMessage());
e.printStackTrace();
}
以上就是Java中文件读写操作的基本实例,包括创建、读取和写入等流程。
还没有评论,来说两句吧...