“Java8输出字符串到文件”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) (创建空白页面) |
Jihongchang(讨论 | 贡献) |
||
第1行: | 第1行: | ||
+ | <syntaxhighlight lang="java"> | ||
+ | import java.io.IOException; | ||
+ | import java.nio.file.Files; | ||
+ | import java.nio.file.Path; | ||
+ | import java.nio.file.Paths; | ||
+ | import java.nio.charset.StandardCharsets; | ||
+ | public class WriteStringToFileUsingFiles { | ||
+ | public static void main(String[] args) { | ||
+ | String content = "这是要写入文件的字符串内容。"; | ||
+ | Path path = Paths.get("output.txt"); | ||
+ | |||
+ | try { | ||
+ | // 使用 Files.write 方法将字符串写入文件 | ||
+ | Files.write(path, content.getBytes(StandardCharsets.UTF_8)); | ||
+ | System.out.println("字符串已成功写入文件。"); | ||
+ | } catch (IOException e) { | ||
+ | System.err.println("写入文件时发生错误: " + e.getMessage()); | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </syntaxhighlight> |
2025年3月5日 (三) 01:08的最新版本
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
public class WriteStringToFileUsingFiles {
public static void main(String[] args) {
String content = "这是要写入文件的字符串内容。";
Path path = Paths.get("output.txt");
try {
// 使用 Files.write 方法将字符串写入文件
Files.write(path, content.getBytes(StandardCharsets.UTF_8));
System.out.println("字符串已成功写入文件。");
} catch (IOException e) {
System.err.println("写入文件时发生错误: " + e.getMessage());
}
}
}