Java 文件到集合

把文件中的数据读取到集合中,并遍历集合

思路:
1.创建字符缓冲输入流对象
2.创建ArrayList集合对象
3.调用字符缓冲输入流对象的方法读取数据
4.把读到的字符串数据存储到集合中
5.释放资源
6.遍历集合

		//1.创建字符缓冲输入流对象
        BufferedReader br = new BufferedReader(new FileReader("D:\\code\\java\\Stream\\Copy7.java"));

        //2.创建ArrayList集合对象
        ArrayList<String> array = new ArrayList<String>();
        
        //3.调用字符缓冲输入流对象的方法读取数据
        String line;
        while((line=br.readLine())!=null) {
            //4.把读到的字符串数据存储到集合中
            array.add(line);
        }

        //5.释放资源
        br.close();

        //6.遍历集合
        for (String s:array){
            System.out.print(s);
        }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java 中,可以通过使用第三方库 SnakeYAML 来解析和生成 YAML 配置文件。下面是一个示例 YAML 配置文件,其中包含一个集合: ``` # 示例 YAML 配置文件 database: driverClass: com.mysql.jdbc.Driver jdbcUrl: jdbc:mysql://localhost:3306/mydatabase username: myusername password: mypassword connectionProperties: autoReconnect: true characterEncoding: UTF-8 useUnicode: true ``` 在 Java 中,可以将上述 YAML 配置文件解析为一个 Map 对象,其中包含一个名为 "database" 的键,对应一个包含多个键值对的子 Map。可以使用以下代码来实现: ```java import java.io.InputStream; import java.util.Map; import org.yaml.snakeyaml.Yaml; public class YamlExample { public static void main(String[] args) { // 加载 YAML 文件 InputStream inputStream = YamlExample.class.getClassLoader().getResourceAsStream("config.yml"); // 解析 YAML 文件为 Map 对象 Yaml yaml = new Yaml(); Map<String, Object> data = yaml.load(inputStream); // 获取集合中的某个属性 Map<String, Object> database = (Map<String, Object>) data.get("database"); String driverClass = (String) database.get("driverClass"); String jdbcUrl = (String) database.get("jdbcUrl"); String username = (String) database.get("username"); String password = (String) database.get("password"); Map<String, Object> connectionProperties = (Map<String, Object>) database.get("connectionProperties"); boolean autoReconnect = (boolean) connectionProperties.get("autoReconnect"); String characterEncoding = (String) connectionProperties.get("characterEncoding"); boolean useUnicode = (boolean) connectionProperties.get("useUnicode"); // 打印输出 System.out.println("driverClass: " + driverClass); System.out.println("jdbcUrl: " + jdbcUrl); System.out.println("username: " + username); System.out.println("password: " + password); System.out.println("autoReconnect: " + autoReconnect); System.out.println("characterEncoding: " + characterEncoding); System.out.println("useUnicode: " + useUnicode); } } ``` 上述代码中,首先使用 SnakeYAML 的 Yaml 类加载 YAML 文件并解析为一个 Map 对象。然后,通过获取 Map 对象中的键值对,可以访问集合中的各个属性。最后,将获取的属性打印输出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

稻田里展望者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值