You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

31 lines
1.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Demo04 {
public static void main(String[] args) {
// 指定要写入的文件路径
String filePath = "example.txt";
// 要写入文件的字符串
String content = "Hello, this is a test string written to a file.";
// 使用try-with-resources语句自动管理资源确保文件正确关闭
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
// 写入字符串到文件
writer.write(content);
// 或者使用newLine()方法写入一个新行
// writer.newLine();
// writer.write("This is on a new line.");
// 注意如果调用了writer.close()则不需要在这里显式调用因为try-with-resources会自动处理
} catch (IOException e) {
// 处理文件写入过程中可能发生的异常
e.printStackTrace();
}
System.out.println("String written to file successfully.");
}
}