import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
public class dianzhaokuozhan {
/*给定一个list集合:{"张柏芝","刘德华","张亮","张靓颖","杨颖","黄晓明"}
1.编写一个方法:将list集合中所有姓张的人员写入到D:\\a.txt中
2.编写一个方法:将D:\\a.txt中所有姓张的人员信息读取出来并打印到控制台上 --->默认不是1问写入的数据
*/
public static void main(String[] args) throws Exception {
ArrayList<String> names=new ArrayList<String>();
Writer out = new FileWriter("D:\\a.txt");
BufferedWriter fw= new BufferedWriter(out);
//向集合中添加元素
Collections.addAll(names, "张柏芝","刘德华","张亮","张靓颖","杨颖","黄晓明");
//遍历集合,以张开头的写在D:\\a.txt
for (String thisname : names) {
if(thisname.startsWith("张")){
fw.write(thisname);
}
}
fw.close();
//读取文件
Reader in = new FileReader("D:\\a.txt");
BufferedReader fr= new BufferedReader(in);
String line = null;
while(null!=(line = fr.readLine())) {
String [] arr=line.split("张");
for (int i = 0; i < arr.length; i++) {
System.out.println("张"+arr[i]);
}
}
fr.close();
}
}
不用换行的做法 |