1

이 input.txt를 2D 배열로 만들려고합니다. 나는 몇 가지 다른 방법을 시도했다. 이것은 나의 최신 시도이며, 나는 여기 붙어있는 것 같습니다 ... 어떤 도움을 많이 주시면 감사하겠습니다.텍스트 파일의 자바 2D 배열

input.txt 구조 : SCI2000/Science/1200/10/C -> 23 개의 행과 5 개의 열이 있습니다. 각 열에 제목을 붙이고 싶습니다.

FileReader fr = new FileReader("input.txt"); 
    BufferedReader br = new BufferedReader(fr); 
    StringBuilder sb = new StringBuilder(); 
    String line = br.readLine(); 

    while (line != null) { 
     sb.append(line); 
     sb.append(System.lineSeparator()); 
     line = br.readLine(); 
    } 
    String everything = sb.toString(); 
    String[][] input = new String[23][5]; 
    String[] tokens = everything.split("/"); 
    for(String str : tokens) 
     System.out.print(str); 
+1

'input.txt'의 구조는 무엇입니까? 샘플 데이터와 어떻게 배열에 배치해야하는지 알려주시겠습니까? –

+0

input.txt 구조체 : SCI2000/Science/1200/10/C -> 23 개의 행과 5 개의 열이 있습니다. 각 열에 제목을 붙이고 싶습니다. – Bob

답변

0

그냥 주 처리 부분 (테스트하지) :

int columns = 5; 
String[] row = String[columns]; 
int j = 0; 

while ((line = br.readline) != null) { 
    row = line.split("/"); 
    for(int i=0; i<row.length; ++i) { 
     input[j,i] = row(i); 
    } 
    ++j; 
} 
0
FileReader fr = new FileReader("input.txt"); 
BufferedReader br = new BufferedReader(fr); 
String[][] input = new String[24][5]; // 1 row for title, 23 rows for data 

// add title 
input[0] = new String[]{"title1", "title1", "title1", "title1", "title1"}; 
String line = br.readLine(); 
int row = 1; // update here 

while ((line = br.readLine())!= null) { 
    input[row++] = line.split("/"); 
} 

// print all data 
for (int i = 0; i < input.length; i++) { 
    for (int j = 0; j < input[i].length; j++) 
     System.out.print(input[i][j] + " "); 

    //new line 
    System.out.println(); 
} 
+0

제목이 표시되지 않습니다. 대신이 배열은 2D 배열의 마지막 행으로 표시됩니다. -> "null null null null null ". 어떤 제안? – Bob

+0

'int row = 0'을'int row = 1'로 변경합니다. 행 0이 이미 title에 사용 되었기 때문입니다. – qkzhu