天天看點

讀取日志檔案中某一列的值

接到任務,讓我統計一下有多少個使用者id,咋一看,一大把密密麻麻的數字,但仔細一看,也不是無章可循的,經過幾分鐘的倒騰,終于弄出來了

package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

public class Demo {

    public static void main(String[] args) throws Exception {
        // 以逗号為分割,統計第二列的不重複的值
        String filePath = "src/login_2015-04-09.log";
        int i = ;
        count(filePath, i);
    }

    private static void count(String filePath, int i) throws Exception {
        String[] str = new String[];
        try {
            String encoding = "UTF-8";
            File file = new File(filePath);
            if (file.isFile() && file.exists()) { // 判斷檔案是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);// 考慮到編碼格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                Set<String> ignoreChars = new HashSet<String>();
                while ((lineTxt = bufferedReader.readLine()) != null) {

                    str = lineTxt.split(",");
                    System.out.println(str[] + "=====");
                    ignoreChars.add(str[i]);

                }

                System.out.println(ignoreChars.size());
                read.close();
            } else {
                System.out.println("找不到指定的檔案");
            }
        } catch (Exception e) {
            System.out.println("讀取檔案内容出錯");
            e.printStackTrace();
        }

    }

}