java保存字符串到文件
时间: 2023-12-19 18:04:50 浏览: 26
可以使用Java中的FileWriter和BufferedWriter类来将字符串保存到文件中。以下是一个示例代码:
```java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class SaveStringToFile {
public static void main(String[] args) {
String content = "这是要保存的字符串内容";
String filePath = "C:\\example\\file.txt"; // 文件路径
try {
File file = new File(filePath);
// 如果文件不存在,则创建文件
if (!file.exists()) {
file.createNewFile();
}
// 使用FileWriter和BufferedWriter将字符串写入文件
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("内容已经成功写入文件!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
你可以将"这是要保存的字符串内容"替换为你要保存的字符串,将"C:\\example\\file.txt"替换为你想要保存到的文件路径。运行代码后,你就可以在指定的文件路径下找到保存的内容了。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)