阶段总结:java处理csv文件

  • 公司的Java研修也结束了。然后一看这最后一个练习题,竟然是处理csv文件,还是有点亲切感的。以前用Python写得多一点,虽然现在都有些忘了怎么写,不过还是记得Python写会简单一些。为了不忘记Java怎么写,就记录一下这个题吧。

  • 题目:大体上就是读取下图格式的csv文件,计算每个科目的平均分、每个人的平均分和总分,输出为txt文件。
    阶段总结:java处理csv文件_第1张图片

  • 代码:

import java.io.*;

public class Stat_csv2txt {

	public static int getMaxRow(File f) throws IOException {
		System.out.println("----getMaxRow");
		BufferedReader br = new BufferedReader(new FileReader(f));
		String str;
		int maxRow = 0;
		while ((str = br.readLine()) != null) {
			maxRow++;
		}
		br.close();
		return maxRow;
	}

	public static void main(String[] args) throws IOException {
		File f = new File("Csv.csv");

		int rows = getMaxRow(f);
		int cols = 6;
		String[][] arr = new String[rows][cols];

		System.out.println("----Reading File to Array");
		BufferedReader br = new BufferedReader(new FileReader(f));
		String str;

		for (int i=0; i<rows; i++) {
			str = br.readLine();
			String[] tmp = str.split(",");
			for (int j=0; j<cols; j++) {
				arr[i][j] = tmp[j];
			}
		}
		br.close;

		System.out.println("----Calculate and Write");
		PrintWrite pw = new PrintWrite(new BufferWrite(new FileWrite("Txt.txt")));

		double sumKoku = 0;
		double sumSansu = 0;
		double sumRika = 0;
		double sumSyakai = 0;
		double sumPerson = 0;

		for (int i=1; i<rows; i++) {
			sumPerson = 0;

			for (int j=2; j<cols; j++) {
				sumPerson += Integer.parseInt(arr[i][j]);
			}

			sumKoku += Integer.parseInt(arr[i][2]);
			sumSansu += Integer.parseInt(arr[i][3]);
			sumRika += Integer.parseInt(arr[i][4]);
			sumSyakai += Integer.parseInt(arr[i][5]);

			System.out.println("[" + arr[i][0] + ", " + arr[i][1] + ": " + sumPerson/(rows-1) + ", " + sumPerson + "]");	
		}

		pw.println("aveKoku: " + sumKoku/(rows-1));
		pw.println("aveSansu: " + sumSansu/(rows-1));
		pw.println("aveRika: " + sumRika/(rows-1));
		pw.println("aveSyakai: " + sumSyakai/(rows-1));

		pw.close();

		System.out.println("----Done");

	}
}

以上。

你可能感兴趣的:(阶段总结:java处理csv文件)