3、使用IO流将List集合内容写入指定文件

编程题目:

3.向list集合添加姓名{张三,李四,王五,二丫,钱六,孙七},将二丫替换为王小丫,写入到"D:\stuinfo.txt"。

示例代码:

package program.stream.exercise03;

import java.io.*;
import java.util.*;

/**
 * 3.向list集合添加姓名{张三,李四,王五,二丫,钱六,孙七},将二丫替换为王小丫,写入到"D:\\stuinfo.txt"
**/

public class ListWriter {
	public static void main(String[] args) {

		List<String> list = new ArrayList<String>();
		
		//向list集合添加姓名{张三,李四,王五,二丫,钱六,孙七},
		list.add("张三");
		list.add("李四");
		list.add("王五");
		list.add("二丫");
		list.add("钱六");
		list.add("孙七");
		
		System.out.println("List修改前遍历:");
		for(String s : list){
			System.out.println(s);
		}
		
		//将二丫替换为王小丫,
		list.set(3, "王小丫");
		
		System.out.println("List修改后遍历:");
		Iterator<String> iterator = list.iterator();
		while (iterator.hasNext()) {
			String s = (String) iterator.next();
			System.out.println(s);
		}
		
		//写入到"D:\\stuinfo.txt"
		Writer write = null;
		BufferedWriter bufferedWriter = null;
		
		try {
			write = new FileWriter("D:\\stuinfo.txt");
			bufferedWriter = new BufferedWriter(write);
			
			for(int i=0;i<list.size();i++){
				bufferedWriter.write(list.get(i)+"\r\n");//写入换行
			}
			System.out.println("写入完成!");
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				bufferedWriter.flush();
				write.flush();
				bufferedWriter.close();
				write.close();
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}

}

结果显示:

3、使用IO流将List集合内容写入指定文件_第1张图片
3、使用IO流将List集合内容写入指定文件_第2张图片

你可能感兴趣的:(Java编程(Java,Program),#,Java编程04:IO流)