案例:集合到文件

9acbe0452b03dbabb19898ef5cca2592.png

public class ArrayListToTxtDemo {
    public static void main(String[] args) throws IOException {
        //创建ArrayList集合
        ArrayList<String> arrayList = new ArrayList<String>();

        //往集合中存储字符串元素
        arrayList.add("hello");
        arrayList.add("world");
        arrayList.add("中国");

        //创建字符缓冲输出流对象
        BufferedWriter bw = new BufferedWriter(new FileWriter("myFile\\bw.txt"));

        //遍历集合
        for (String s : arrayList){
            //调用字符缓冲输出流对象的方法写数据
            bw.write(s);
            bw.newLine();  // 特有功能:换行
            bw.flush();
        }

        //释放资源
        bw.close();
    }
}

运行结果:

猜你喜欢

转载自www.cnblogs.com/pxy-1999/p/12713787.html
今日推荐