package three;import javaio;import javautil;public class three public static void mainString args SetString names = new HashSetArraysasList李一 张三 李四 王五 赵六; try BufferedWriter writer
- package three; - 声明该类所在的包为three
- import java.io.*; - 导入java.io包,包含文件读写相关的类和接口
- import java.util.*; - 导入java.util包,包含集合相关的类和接口
- public class three { - 声明一个公共类three
- public static void main(String[] args) { - 声明一个公共静态方法main,参数为字符串数组args
- Set
names = new HashSet<>(Arrays.asList("李一", "张三", "李四", "王五", "赵六")); - 创建一个字符串类型的集合names,使用HashSet实现,初始值为一个包含五个字符串的列表 - try (BufferedWriter writer = new BufferedWriter(new FileWriter("C:\Users\Administrator\IdeaProjects\untitled\src\three\three.txt"))) { - 使用try-with-resources语句创建一个BufferedWriter对象writer,将其与一个FileWriter对象关联,以便将输出写入指定的文件
- for (String name : names) { - 对names集合中的每个元素执行以下操作,将元素赋值给变量name
- writer.write(name); - 将变量name的值写入BufferedWriter对象writer中
- writer.newLine(); - 在BufferedWriter对象writer中写入一个新行
- System.out.println("Names added to file successfully."); - 输出一条成功的消息
- } - 结束for循环
- } catch (IOException e) { - 捕获IOException异常
- System.out.println("Error writing to file: " + e.getMessage()); - 输出错误消息和异常信息
- } - 结束try-catch语句
- } - 结束main方法
- } - 结束类定
原文地址: https://www.cveoy.top/t/topic/fq3I 著作权归作者所有。请勿转载和采集!