java 21 - 10 文本文件和集合之间互相存储数据

有时候,我们会遇到单独写入数据到文本文件的情况。比如:

   需求:把ArrayList集合中的字符串数据存储到文本文件

   分析:

      A:ArrayList集合中存储的是String类

      B:要存储的文件是文本文件,所以用字符流,为了快速,用缓冲字符流A

   数据源:

      ArrayList<String>  -----  遍历集合,得到数据  

     目的地:

      c.txt  ------  FileWriter  ------ BufferedWriter

 

 1     public static void main(String[] args) throws IOException {
 2         // 封装数据(创建集合对象)
 3         ArrayList<String> arry = new ArrayList();
 4         //添加数据
 5         arry.add("我");
 6         arry.add("要");
 7         arry.add("睡觉。。");
 8         
 9         //封装目的地
10         BufferedWriter bw = new BufferedWriter(new FileWriter("c.txt"));
11         String line = null;
12         int len = 0;
13         //遍历数组,写入数据到目的地
14         for(String s : arry){
15             bw.write(s);
16             bw.newLine();
17             bw.flush();
18         }
19         bw.close();
20 
21     }

 

同样,有时候我们需要从文本文件中提取里面的数据,并存储到集合中:

  需求:从文本文件中读取数据(每一行为一个字符串数据)到集合中,并遍历集合

  分析:

    A:从文本文件中读取数据,则用缓冲字符输入流 BufferReader

    B:因为为了快速,使用的是每一行为一个字符串数据的读取方式,所以集合类型为String类的

  数据源:
      copy.txt -- FileReader -- BufferedReader
    目的地:
      ArrayList<String>

 1 public static void main(String[] args) throws IOException {
 2         // 封装数据源
 3         BufferedReader br = new BufferedReader(new FileReader("copy.txt"));
 4         // 封装目的地(创建集合)
 5         ArrayList<String> arry = new ArrayList();
 6         //从数据源中读取数据,并把数据写入集合中
 7         String line = null;
 8         while((line = br.readLine()) != null){
 9             arry.add(line);
10         }
11         br.close();
12         
13         //遍历数组
14         for(String s : arry){
15             System.out.println(s);
16         }
17 
18     }

 

转载于:https://www.cnblogs.com/LZL-student/p/5926623.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值