1. 程式人生 > >BufferedReader和BufferedWriter讀取和寫入資料

BufferedReader和BufferedWriter讀取和寫入資料

import java.util.*;
import java.io.*;
public class Score{
    public static void main(String args[]) throws Exception{
        String pathname=new String("//Users//wangxi//Documents//Score.txt");
        File file=new File(pathname);
        BufferedReader reader=new BufferedReader(new FileReader(file));
        List<Integer> score=new ArrayList<Integer>();
        String str;
        while((str=reader.readLine())!=null) {
            String temp[]=str.split("\\s+");//正則表示式分割字串
            for(int i=0;i<temp.length;i++) {
                score.add(Integer.parseInt(temp[i]));
            }
        }
        reader.close();
        int max_score=score.get(0);
        int min_score=score.get(0);
        int sum=score.get(0);
        for(int i=1;i<score.size();i++) {
            int temp=score.get(i);
            sum+=temp;
            if(temp<min_score)
                min_score=temp;
            if(temp>max_score)
                max_score=temp;
        }
        double avg_score=(sum-max_score-min_score)*1.0/(score.size()-2);
        System.out.println("最高分:"+max_score);
        System.out.println("最低分:"+min_score);
        System.out.println("平均分:"+avg_score);

        File outpath=new File("//Users//wangxi//result.txt");
        BufferedWriter out=new BufferedWriter(new FileWriter(outpath)); //非追加模式
        out.write("最高分:"+max_score);
        out.newLine();
        out.write("最低分:"+min_score);
        out.newLine();
        out.write("平均分:"+avg_score);
        out.newLine();
        out.flush();
        out.close();
    }
}