2013-02-27 2 views
0

CSV 파일을 Java의 2D 배열로 변환하는 데 문제가 있습니다. 이 문제를 해결하는 데 가장 길게 갈 수도 있지만 왜 오류가 발생하는지 파악할 수는 없습니다. 각 행과 열에는 각각 25 개의 요소가 있어야합니다. 여기 내 코드는 다음과 같습니다.CSV 파일을 2D 배열로 변환 Java

BufferedReader CSVFile = new BufferedReader(new FileReader(fileName)); 

String dataRow = CSVFile.readLine(); 
// Read first line. 
// The while checks to see if the data is null. If 
// it is, we've hit the end of the file. If not, 
// process the data. 

while (dataRow != null) { 
    dataRow.split(","); 
    list.add(dataRow); 
    dataRow = CSVFile.readLine(); 

    // Read next line of data. 
} 
// Close the file once all data has been read. 
CSVFile.close(); 

String[] tokens = null; 
Object[] test = list.toArray(); 

String[] stringArray = Arrays.copyOf(test, test.length, String[].class); //copies the object array into a String array 

//splits the elements of the array up and stores them into token array 

for (int a = 0; a < test.length; a++) { 
    String temp = stringArray[a]; 
    tokens = temp.split(","); 

} 

//converts these String tokens into ints 

int intarray[] = new int[tokens.length]; 

for (int i = 0; i < tokens.length; i++) { 

    intarray[i] = Integer.parseInt(tokens[i]); 

} 

//attempts to create a 2d array out of a single dimension array 
int array2d[][] = new int[10][3]; 

for (int i = 0; i < 25; i++) { 
    for (int j = 0; j < 25; j++) { 
     array2d[i][j] = intarray[(j * 25) + i]; 

    } 
} 

나는 ArrayList가 첫 번째 String 배열로 복사되지만 확신 할 수없는 오류라고 생각합니다. 이 파일에는 25 개의 열과 25 개의 행이 있습니다. 내가 계속 오류 배열은 인덱스 25에서 범위를 벗어났다는 것입니다. 어떤 입력 크게 감사하겠습니다. 감사!

+0

목록은 무엇인가? 나는 그것이 선언 된 것을 보지 못한다. –

+0

어떤 배열입니까? array2d 또는 intarray? 어떤 라인? – Dan

+0

데이터 행 루프에서 Object가 필요하다고 생각하지 않습니다. readLine은 문자열을 반환합니다. –

답변

3
for (int a = 0; a < test.length; a++) { 
    String temp = stringArray[a]; 
    tokens = temp.split(","); //< -- OLD VALUE REPLACED WITH NEW SET OF TOKENS 

} 

tokens 사용 된 마지막 문자열의 토큰, 하지 지금까지 본 토큰을 모두 포함됩니다. 따라서 tokens.length == 25이고 tokens[25]에 액세스하는 것은 ArrayOutOfBounds 예외입니다.

당신은 아래

ArrayList<String> tokens = new ArrayList<String>(); 
... 
tokens.addAll(Arrays.asList(temp.split(","))); 

Create ArrayList from array는 ArrayList의에 요소의 배열을 추가하는 방법에 대해 설명 변경해야합니다.

+0

입력 해 주셔서 감사합니다. 나는 당신이하려고하는 것에 대한 논리를 분명히 본다. 그러나 temp.split (",")을 ArrayList 토큰에 추가하려고하면 오류가 발생합니다. ArrayList 형식의 addAll (Collection ) 메서드는 인수 (String [])에 적용 할 수 없습니다. 이게 왜 나에 대한 아이디어입니까? 다시 한번 감사드립니다. – Chase552

+0

@ user2077526 아 지저분 해 ..'Arrays.asList'를 사용해야합니다. –

1

그건 그렇고 숙제가 아니라면 자신의 CSV 구문 분석을하는 것이 아마도 시간을 가장 효율적으로 사용하는 것은 아닐 것입니다.

StrTokenizer tokenizer = StrTokenizer.getCSVInstance(); 

while (...) { 
    tokenizer.reset(dataLine); 
    String tokens[] = tokenizer.getTokenArray(); 
    ... 
} 
: 큰 라이브러리는 여기에

은 평민 - lang3와 예입니다 .... 등 빈 토큰 구성 구분 기호를 인용 같은 것들과 그 거래를이 (opencsv, 공유지 - lang3)을 처리하기 위해 거기에있다

이제 파싱의 평범한 행위가 아닌 데이터로 수행하려는 실제 논리에 집중할 수 있습니다.

그리고 당신은 단순 목록으로 토큰을 수집에만 관심이 있다면 :

StrTokenizer tokenizer = StrTokenizer.getCSVInstance(); 
List<String> allTokens = new ArrayList<String>(); 
while (...) { 
    tokenizer.reset(dataLine); 
    allTokens.addAll(tokenizer.getTokenList()); 
    ... 
}