1.用Java语言编写程序,向一个文件中写入多行文本,并读取写入的文本显示在屏幕上。
时间: 2024-10-20 15:19:36 浏览: 25
在Java中,你可以使用`BufferedWriter`和`Scanner`类来实现文件的读写操作。下面是一个简单的示例:
首先,我们需要创建一个文件写入的方法,向文件中添加多行文本:
```java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public void writeToFile(String filename, String... lines) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
for (String line : lines) {
writer.write(line + "\n"); // 每行结尾添加换行符
}
writer.close();
} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
}
}
```
然后,我们可以创建一个方法来读取并显示文件内容:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public void readFromFile(String filename) {
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
System.out.println("Error reading from file: " + e.getMessage());
}
}
```
最后,在主函数中调用这两个方法:
```java
public static void main(String[] args) {
String inputFile = "example.txt";
String[] linesToWrite = {"这是第一行", "这是第二行", "这是第三行"};
writeToFile(inputFile, linesToWrite);
readFromFile(inputFile);
阅读全文