2014-12-10 5 views
1

따라서 할당은 이름, 시간 및 출신 국가와 같은 항목이 포함 된 CSV 파일을 읽고 콘솔에 인쇄하는 것입니다. 나는 그것을 반복하는 방법을 알아 냈다. 그러나 첫 번째 라인 이후에, 나는 얻는 것이 모두 백개 정도의 출력을 위해 null이다. 여기에는 개별 이름 시간 등이 있어야한다. 여기에 내가 가진 것이있다.JAV에서 CSV 파일 읽기 및 인쇄

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

답변

0

각 줄 끝에서 index을 0으로 재설정해야합니다.

+1

감사합니다! 그것은 그것을 고쳤다. – Newt

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 클래스에서 모든 if가있는 함수를 만들고 Stringint 매개 변수를 사용합니다.

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