在JAVA中读取和打印CSV文件

时间:2014-12-10 05:43:01

标签: java csv java.util.scanner

因此,分配是读取包含名称,时间和原产国等项目的CSV文件,然后将它们打印到控制台。我已经想出如何循环它但是在第一行之后,我得到的所有东西都是null,因为下一百个左右的输出应该包含单独的名称等等。这就是我所拥有的。

public class CSVReader {

    public static void main(String[] args) throws IOException{
        // TODO Auto-generated method stub

        Scanner Scan = new Scanner(new File("./src/marathon.csv"));
        Scanner timeScan = null;

        int index = 0;

        List<Racer> racerList = new ArrayList<>();

        while(Scan.hasNextLine()){
            timeScan = new Scanner(Scan.nextLine());
            timeScan.useDelimiter(",");
            Racer racer = new Racer();

            while(timeScan.hasNext()){

                String data = timeScan.next();
                if(index==0)
                    racer.setFirstName(data);
                else if(index==1)
                    racer.setLastName(data);
                else if(index==2)
                    racer.setSexAge(data);
                else if(index==3)
                    racer.setCountry(data);
                else if(index==4)
                    racer.setPlace(data);
                else if(index==5)
                    racer.setGunTime(data);
                else if(index==6)
                    racer.setNetTime(data);
                else if(index==7)
                    racer.setKm5(data);
                else if(index==8)
                    racer.setKm10(data);
                else if(index==9)
                    racer.setKm15(data);
                else if(index==10)
                    racer.setKm20(data);
                else if(index==11)
                    racer.setKm25(data);
                else if(index==12)
                    racer.setKm30(data);
                else if(index==13)
                    racer.setKm35(data);
                else if(index==14)
                    racer.setKm40(data);
                else if(index==15){
                    racer.setMinutesPerMile(data);
                }
                index++;
            }
            racerList.add(racer);
        }
        System.out.println(racerList);
    }
}

3 个答案:

答案 0 :(得分:0)

您需要在每行之后将index重置为0.

答案 1 :(得分:0)

问题是您忘记在while循环开始时将index变量重置为0。在得到字符串之前,只需在while循环中移动index声明:

while(timeScan.hasNext()){
    int index = 0
    String data = timeScan.next();
    if(index==0)
        //Rest of your code, if's, etc

在扫描仪声明后,不要忘记将它从当前的位置删除:

Scanner Scan = new Scanner(new File("./src/marathon.csv"));
Scanner timeScan = null;

//int index = 0; //Remove this line from here

另外,您可能会考虑稍微更改一下代码,这就是很多if语句,提示:在Racer类中创建一个包含所有ifs的函数,然后使用Stringint参数。

答案 2 :(得分:0)

CSV文件在第一行包含一个特殊行,其中包含以逗号分隔的字段名称

import java.io.IOException;
import java.util.ArrayList;

public class CSV {
public String[] header=null;
public String[][] table=null;

/**
 * This method reads file lines into ArrayList, 
 * @param fileName  the file to read from
 * @return ArrayList of lines read
 * @author Amr Lotfy
 * 
 */
public static ArrayList<String> load(String fileName){ 
    ArrayList<String> lines=new ArrayList<String>();
    if ((fileName!=null)&&(new File(fileName).exists())){
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(fileName));
            try {
                String line;

                while ((line = br.readLine()) != null) {
                    // process the line.
                    //add to value list
                    lines.add(line);
                }
            } catch (IOException e) {
                Logging.log(e.toString());
            }
            try {
                br.close();
            } catch (IOException e) {
                Logging.log(e.toString());
            }
        } catch (FileNotFoundException e) {
            Logging.log(e.toString());
        }
    }
    return lines;
}   

public CSV(String fileName) throws Exception{
    ArrayList<String> lines=load(fileName);
    if ((lines!=null)&&(lines.size()>0)){
        header=lines.get(0).split(",");
        table=new String[lines.size()-1][header.length];
        for(int i=1; i<lines.size();i++){
            String[] terms=lines.get(i).split(",");
            for (int j=0;j<terms.length;j++){
                table[i-1][j]=terms[j];
            }

        }
    } else{
        Logging.log("unable to load csv file.");
    }

}



public String get(int rowIndex, String colHeader) throws Exception{
    String result=null;
    int colNumber=-1;
    if (rowIndex>=0 && rowIndex<table.length){
        for (int i=0; i<header.length;i++){
            if (colHeader.equalsIgnoreCase(header[i])){
                colNumber=i;
                break;
            }
        }
        if (colNumber!=-1){
            result=table[rowIndex][colNumber];
        }
    }
    return result;
}
}

样本用法:

public void loadServerMap(String fileName) throws Exception{
    String alias,url;
    CSV csv=new CSV(fileName);
    if (csv.table.length>0){
        for (int i=0;i<csv.table.length;i++){
            alias=csv.get(i, "alias");
            url=csv.get(i, "url");
            // You can print here but I will put the result in a map
            serverMap.put(alias, url);
        }
    }
}