理解Java标准库中的IO操作:文件读写示例
在Java中,标准库中的java.io
包提供了各种类型的输入/输出流,用于进行文件读写等IO操作。
以下是一个简单的文件读写示例:
- 文件写入:
```java
import java.io.*;
public class FileWriteExample {
public static void main(String[] args) {
String content = “Hello, World!”; // 要写入的文本
try (FileWriter writer = new FileWriter("myFile.txt")); // 创建一个FileWriter对象,指定要写的文件名
writer.write(content); // 将内容写入到文件中
} catch (IOException e) {
System.out.println("Error occurred while writing to file: " + e.getMessage());
}
}
}
2. 文件读取:
```java
import java.io.*;
public class FileReadExample {
public static void main(String[] args) {
String content;
try (FileReader reader = new FileReader("myFile.txt")); // 创建一个FileReader对象,指定要读取的文件名
content = new String(reader.read()); // 从文件中读取一行内容(这里只读取了一行)
} catch (IOException e) {
System.out.println("Error occurred while reading from file: " + e.getMessage());
}
if (content != null && !content.isEmpty()) {
System.out.println(content);
}
}
}
以上示例展示了如何使用Java标准库中的FileWriter
和FileReader
进行文件读写操作。
还没有评论,来说两句吧...