BufferedReader和BufferedWriter读写文件

本文介绍如何使用Java编程语言实现学生信息的读取、存储、排序与输出功能,涉及使用类、接口、集合、文件操作等核心知识点,特别强调了通过泛型确保代码的类型安全性和复用性。通过实例演示了如何利用Java中的Comparator接口进行复杂的数据排序,包括按得分从高到低及得分相同时按出生日期升序排序。最后,展示了如何将排序后的学生信息写入新的文本文件中,确保输出格式与输入一致。此教程对于初学者理解和掌握Java基础数据结构、算法排序以及文件操作提供了实践指导。

1.创建Student类存储每个学生信息,属性(学号,姓名,出生日期,得分)
2.从c:/test/student.txt文件中读取学生信息。如下:
       学号,姓名,出生日期,得分
       1,张三,1982-1-1,80
       2,李四,1982-11-15,40
       3,王五,1982-2-8,60
       4,赵六,1982-7-5,70
       5,小明,1981-12-21,70
       6,李大嘴,1982-1-3,70
3.使用List存储6名学生的信息。
4.使用集合排序,将学生信息按时得分从高到低排序,得分相同时按照出生日期升序排序。
5.输出排序后的结果到c:/test/result.txt文件中,输出格式与输入格式相同,第一行是表头。
6.在代码中使用泛型,读文本文件使用BufferedReader,写文本文件使用BufferedWriter

解:
1.创建StudentInfo类,实现Comparable接口

package com.test;  
 
import java.text.ParseException;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
 
public class StudentInfo implements Comparable<StudentInfo>  
{  
    private String id;          //学号  
    private String name;        //学生姓名  
    private String birthday;    //出生日期  
    private String score;       //分数  
 
    public String getId()  
    {  
        return id;  
    }  
 
    public void setId(String id)  
    {  
        this.id = id;  
    }  
 
    public String getName()  
    {  
        return name;  
    }  
 
    public void setName(String name)  
    {  
        this.name = name;  
    }  
 
    public String getBirthday()  
    {  
        return birthday;  
    }  
 
    public void setBirthday(String birthday)  
    {  
        this.birthday = birthday;  
    }  
 
    public String getScore()  
    {  
        return score;  
    }  
 
    public void setScore(String score)  
    {  
        this.score = score;  
    }  
 
    /**  
     *   
     * {排序方法}  
     *   
     * @param objStu  
     * @return  
     * @author:LJ  
     */ 
    public int compareTo(StudentInfo objStu)  
    {  
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
        //得分相同时按照出生日期升序排序  
        if (this.score.equals(objStu.getScore()))  
        {  
            //格式化日期字符串  
            Date date1 = null;  
            try 
            {  
                date1 = dateFormat.parse(this.birthday);  
            }  
            catch (ParseException e1)  
            {  
                e1.printStackTrace();  
            }  
            Date date2 = null;  
            try 
            {  
                date2 = dateFormat.parse(objStu.getBirthday());  
            }  
            catch (ParseException e2)  
            {  
                e2.printStackTrace();  
            }  
            //出生日期升序排序  
            return date1.compareTo(date2);  
        }  
        //得分从高到低排序  
        return objStu.getScore().compareTo(this.score);  
    }  
}  

2.读写文件类StudentFile.java

package com.test;  
 
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;  
 
public class StudentFile  
{  
    /**  
     *   
     * {根据路径读取学生文件信息}  
     *   
     * @param path  
     * @return List<StudentInfo>  
     * @throws Exception  
     * @author:LJ  
     */ 
    public List<StudentInfo> readFile(String path) throws Exception  
    {  
        List<StudentInfo> studentList = new ArrayList<StudentInfo>();  
        BufferedReader br = null;  
        try 
        {  
            br = new BufferedReader(new FileReader(path));  
            String line = null;  
            StudentInfo student = null;  
            while ((line = br.readLine()) != null)  
            {  
                student = new StudentInfo();  
                //将字符串分割成字符串数组  
                String[] studentStr = line.split(",");  
                student.setId(studentStr[0]);  
                student.setName(studentStr[1]);  
                student.setBirthday(studentStr[2]);  
                student.setScore(studentStr[3]);  
                studentList.add(student);  
            }  
        }  
        catch (FileNotFoundException e)  
        {  
            throw new Exception("源文件未找到", e);  
        }  
        catch (IOException e)  
        {  
            throw new Exception("读文件异常.", e);  
        }  
        finally 
        {//资源关闭  
            if (br != null)  
            {  
                try 
                {  
                    br.close();  
                }  
                catch (IOException e)  
                {  
                    e.printStackTrace();  
                }  
            }  
        }  
        return studentList;  
    }  
    /**  
     *   
     * {将学生信息写入目标文件}  
     *   
     * @param studentList  
     * @param dstPath  
     * @throws Exception  
     * @author:LJ  
     */ 
    public void writeFile(List<StudentInfo> studentList, String dstPath) throws Exception  
    {  
        BufferedWriter bw = null;  
        try 
        {  
            bw = new BufferedWriter(new FileWriter(dstPath));  
            if (studentList != null && !studentList.isEmpty())  
            {  
                for(StudentInfo stu:studentList)  
                {  
                    bw.write(stu.getId()+","+stu.getName()+","+stu.getBirthday()+","+stu.getScore());  
                    bw.newLine();//换行  
                }  
            }  
            bw.flush();//强制输出缓冲区的内容,避免数据缓存,造成文件写入不完整的情况。  
        }  
        catch (IOException e)  
        {  
            throw new Exception("目标文件未找到", e);  
        }  
        finally 
        {   //资源关闭  
            if (bw != null)  
            {  
                try 
                {  
                    bw.close();  
                }  
                catch (IOException e)  
                {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }  
} 

3.编写main方法

package com.test;  
 
import java.io.File;  
import java.util.ArrayList;  
import java.util.Collections;  
import java.util.List;  
 
public class Test  
{  
    /**  
     * {main方法}  
     *   
     * @param args  
     * @author:LJ  
     * @throws Exception   
     */ 
 
    public static void main(String[] args) throws Exception  
    {  
        String srcPath = "C:" + File.separator + "test" + File.separator + "student.txt";  
        String dstPath = "C:" + File.separator + "test" + File.separator + "result.txt";  
        //从源文件读取学生信息  
        StudentFile fileStu = new StudentFile();  
        List<StudentInfo> studentList = fileStu.readFile(srcPath);  
        //临时数组,作排序用  
        List<StudentInfo> tempList = new ArrayList<StudentInfo>();  
        for (int i = studentList.size()-1; i > 0; i--)  
        {  
            //将学生信息存入临时数组,并从原数组中删除,行标题除外  
            tempList.add(studentList.get(i));  
            studentList.remove(i);  
        }  
        //对临时数组进行排序  
        Collections.sort(tempList);  
        for (int i=0,n = tempList.size(); i < n; i++)  
        {  
            //将排序后数组追加到原数组中  
            studentList.add(tempList.get(i));  
        }  
        //将学生信息写入目标文件  
        fileStu.writeFile(studentList, dstPath);  
    }  
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值