java数据保存到文件
时间: 2024-03-09 20:46:50 浏览: 23
要将Java中的数据保存到文件中,可以使用Java的IO类。下面是一个简单的示例代码,演示如何将字符串保存到文件中:
```java
import java.io.FileWriter;
import java.io.IOException;
public class FileIOExample {
public static void main(String[] args) {
String data = "Hello, world!";
try {
FileWriter fileWriter = new FileWriter("output.txt");
fileWriter.write(data);
fileWriter.close();
System.out.println("Data has been written to the file.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
}
}
```
在这个示例中,我们创建了一个名为`FileWriter`的对象,并将要写入文件的数据传递给它的`write`方法。然后,我们关闭文件。如果在写入时出现错误,将会抛出一个`IOException`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)