Java文件和IO操作:读写文件示例
在Java中,我们使用java.io
包来进行文件的读写操作。以下是一些基本的读写文件示例:
- 创建并写入文件:
```java
import java.io.*;
public class WriteFile {
public static void main(String[] args) {
// 创建一个Writer对象,用于向文件写数据
try (Writer writer = new FileWriter(“example.txt”)) {
// 写入一些文本到文件
writer.write(“Hello, World! This is a test file.\n”);
// 关闭writer以释放资源
writer.close();
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
e.printStackTrace();
}
}
}
2. **读取文件内容**:
```java
import java.io.*;
public class ReadFile {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt")))) {
// 逐行读取文件内容
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 关闭reader以释放资源
reader.close();
} catch (IOException e) {
System.err.println("Error reading from file: " + e.getMessage());
e.printStackTrace();
}
}
}
以上示例展示了如何创建文件,写入内容,以及读取文件内容。在实际使用中,请确保你的文件路径正确,否则可能会导致无法找到或者读取到文件的问题。
还没有评论,来说两句吧...