java集合和文件数据互转

一、集合到文件

package com.itbianma01;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class Demo {
    public static void main(String[] args) throws IOException {
        ArrayList<String> array=new ArrayList<>();
        array.add("hello");
        array.add("world");
        array.add("java");
        BufferedWriter bw=new BufferedWriter(new FileWriter("myDemo\\array.txt"));
        for (String s:array){
            bw.write(s);
            bw.newLine();
            bw.flush();
        }
        bw.close();
    }
}

 

二、文件到集合

package com.itbianma01;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class Demo1 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("myDemo\\array.txt"));
        ArrayList<String> array = new ArrayList<>();
        String line;
        while ((line = br.readLine()) != null) {
            array.add(line);
        }
        br.close();
        for (String s : array) {
            System.out.println(s);
        }
    }
}

 

posted @ 2023-12-14 16:48  搬砖滴  阅读(8)  评论(0编辑  收藏  举报