编写java应用程序,输入多行字符串,用文件流的方法写入文件jabc.tmp中,并从文件中读取数据
时间: 2024-02-09 20:08:58 浏览: 78
操作jabc的API
好的,以下是Java代码示例:
```java
import java.io.*;
public class FileIOExample {
public static void main(String[] args) {
// 输入多行字符串
String[] lines = {"Hello World!", "This is line 2.", "And this is line 3."};
// 写入文件
String filename = "jabc.tmp";
try {
FileWriter writer = new FileWriter(filename);
for (String line : lines) {
writer.write(line + "\n");
}
writer.close();
System.out.println("文件写入成功!");
} catch (IOException e) {
System.out.println("出现异常:" + e.getMessage());
}
// 从文件中读取数据
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("出现异常:" + e.getMessage());
}
}
}
```
运行后,程序会输出以下内容:
```
文件写入成功!
Hello World!
This is line 2.
And this is line 3.
```
其中,文件 `jabc.tmp` 中的内容为:
```
Hello World!
This is line 2.
And this is line 3.
```
阅读全文