简体   繁体   English

在JAVA中读取和打印CSV文件

[英]Reading and Printing a CSV File in JAVA

So the assignment is to read in a CSV file containing items such as names, times, and countries of origin and then print them to the console. 因此,分配是读入一个CSV文件,其中包含诸如名称,时间和原产国等项目,然后将它们打印到控制台。 I have figured out how to loop it but after the first line, all I get is null for the next hundred or so outputs that should contain individual names times etc. Here's what I have. 我已经弄清楚了如何循环它,但是在第一行之后,对于接下来的大约一百个应该包含单个名称时间等的输出,我得到的都是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);
    }
}

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

The problem is that you have forgotten to reset your index variable to 0 at the beginning of the while loop. 问题是您忘记了在while循环开始时将index变量重置为0 Just move your index declaration inside the while loop, before you get the String: 在获取String之前,只需在while循环内移动index声明即可:

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

And don't forget to remove it from where you currently have it, after the scanner declaration: 并且不要忘记在扫描程序声明之后从当前位置将其删除:

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

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

Also, you might consider changing your code a bit, that is a lot of if statements, hint: make a function in the Racer class that has all the ifs, and takes a String and int parameters. 另外,您可能会考虑更改代码,这是很多if语句的提示:在Racer类中创建一个具有所有ifs并接受Stringint参数的函数。

CSV files have in the first line a special row that contains the field names separated by commas, 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;
}
}

sample usage: 样本用法:

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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM