package com.practice;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/*给定一个list集合:{"张柏芝","刘德华","张亮","张杰","杨颖","黄晓明"}
1.编写一个方法:将list集合中所有姓张的人员写入到D:\\a.txt中
2.编写一个方法:将D:\\a.txt中所有姓张的人员信息读取出来并打印到控制台上*/
public class Test17 {
public static void main(String[] args) throws Exception {
List<String> list= new ArrayList<>();
list.add("张柏芝");
list.add("刘德华");
list.add("张亮");
list.add("张杰");
list.add("杨颖");
list.add("黄晓明");
demo1(list);
demo2();
}
//输出到控制台
public static void demo2() throws FileNotFoundException, IOException {
BufferedReader br =new BufferedReader(new FileReader("a.txt"));
String b =null;
while((b=br.readLine())!=null){
System.out.println(b);
}
br.close();
}
//打印到文件
public static void demo1(List<String> list) throws IOException {
BufferedWriter bw =new BufferedWriter(new FileWriter("a.txt"));
for (String s : list) {
//判断是否姓张
if(s.startsWith("张")){
//打印,换行
bw.write(s);
bw.newLine();
//bw.write(s+" "); 添加空格
}
}
bw.close();
}
}
|
|