【Java】集合到文件&文件到集合

集合到文件

package LearnJava12;

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

public class ArrayListToTxtDemo {
    public static void main(String[] args) throws IOException {
        ArrayList<String> array=new ArrayList<String>();

        array.add("Hello");
        array.add("World");
        array.add("Java");

        BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\MyProject\\Java\\Demo1\\src\\LearnJava12\\array.txt"));

        for (String s:array){
            bw.write(s);
            bw.newLine();
            bw.flush();
        }
        bw.close();
    }
}

文件到集合

package LearnJava12;

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

public class TxtToArrayListDemo {
    public static void main(String[] args) throws IOException {
        BufferedReader br=new BufferedReader(new FileReader("D:\\MyProject\\Java\\Demo1\\src\\LearnJava12\\array.txt"));

        ArrayList<String> array=new ArrayList<String>();

//        调用字符缓冲流对象的方法读数据
        String line;
        while ((line= br.readLine())!=null){
            array.add(line);
        }
        br.close();
        for (String s:array){
            System.out.println(s);
        }
    }
}

 

posted @ 2022-04-22 11:04  木子欢儿  阅读(56)  评论(0编辑  收藏  举报