将学生信息保存到文件中,格式为.txt
运行成功可以直接搜索studen.txt,直接打开
代码如下
学生类
public class student {
private String name;
private int age;
private double grade;
public student(String name,int age,double grade) {
this.name=name;
this.age=age;
this.grade=grade;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getGrade() {
return grade;
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class studentclass {
private List<student>stuList;
private int size;
public studentclass() {
size=0;
stuList=null;
}
public void createclass() {
String names[]= {"张三","王五","李四","赵六","孙琦"};
double grades[]= {89,90,78,85,73};
int ages[]= {17,20,17,18,19};
size=names.length;
stuList=new ArrayList<student>();
student temp;
for(int i=0;i<size;i++) {
temp=new student(names[i],ages[i],grades[i]);
stuList.add(temp);
}
}
public List<Map<String,String>>formatstudent(){
List fclass=new ArrayList<Map<String,String>>();
Map stu;
for(student s:stuList) {
stu=new HashMap<String,String>();
stu.put("姓名",s.getName());
stu.put("成绩",new Double(s.getGrade()).toString());
fclass.add(stu);
}
return fclass;
}
}
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class FileOperation {
private FileWriter out;
public FileOperation(String fileName)throws IOException{
out=new FileWriter(fileName);
}
public void save(List<Map<String,String>>lst) throws IOException{
for(Map<String,String>m:lst) {
for(Map.Entry entry:m.entrySet()) {
out.write(entry.getKey()+":"+entry.getValue()+"\t");
}
out.write("\r\n");
}
}
public void close() throws IOException{
out.close();
}
}
测试类
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class test {
public static void main(String[] args) {
List<Map<String,String>>lst;
studentclass xq=new studentclass();
xq.createclass();
lst=xq.formatstudent();
try {
FileOperation xqstudent=new FileOperation("student.txt");
xqstudent.save(lst);
xqstudent.close();
System.out.println("文件保存成功!");
}
catch(IOException e) {
System.out.println("IO错误,文件保存失败!");
}
}
}
运行结果