javaoop i/o将天气情况记录到文本文件中并读取代码
时间: 2023-04-09 17:04:45 浏览: 217
以下是一个简单的 Java OOP I/O 代码示例,可以将天气情况记录到文本文件中并读取:
```java
import java.io.*;
public class WeatherRecorder {
private String fileName;
public WeatherRecorder(String fileName) {
this.fileName = fileName;
}
public void recordWeather(String weather) {
try {
FileWriter writer = new FileWriter(fileName, true);
writer.write(weather + "\n");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String readWeather() {
StringBuilder sb = new StringBuilder();
try {
FileReader reader = new FileReader(fileName);
BufferedReader br = new BufferedReader(reader);
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
```
使用示例:
```java
WeatherRecorder recorder = new WeatherRecorder("weather.txt");
recorder.recordWeather("Today is sunny.");
recorder.recordWeather("Tomorrow will be cloudy.");
String weatherHistory = recorder.readWeather();
System.out.println(weatherHistory);
```
输出:
```
Today is sunny.
Tomorrow will be cloudy.
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)