2009-11-12 5 views
0

안녕하세요,이 사람은 my previous question의 후속 조치입니다. 지금은이 같은 형식의 텍스트 파일이 있습니다텍스트 파일을 Java의 2 차원 비정형 배열로 가져 오기

100 200 
123 
124 123 145 

내가하고 싶은 것은 자바의 두 차원 불규칙 배열로이 값을 얻을 수있다. 는 내가 지금까지 가지고하는 것은 이것이다 :

public String[][] readFile(String fileName) throws FileNotFoundException, IOException { 
     String line = ""; 
     ArrayList rows = new ArrayList(); 


     FileReader fr = new FileReader(fileName); 
     BufferedReader br = new BufferedReader(fr); 

     while((line = br.readLine()) != null) { 
     String[] theline = line.split("\\s");//TODO: Here it adds the space between two numbers as an element 
     rows.add(theline); 
     } 
     String[][] data = new String[rows.size()][]; 
     data = (String[][])rows.toArray(data); 
     //In the end I want to return an int[][] this a placeholder for testing 
     return data; 

여기 내 문제는 라인 (100) (200) 변수 "theline는"그 다음 내가 원하는 무엇 rows.add(theline) 와 행에에 전달 세 가지 요소를 {"100","","200"}가에 대한 예를 들어, 숫자 만 가지고 가능하면이 String [] [] 배열을 int [] [] 배열 int로 변환하여 반환하는 방법입니다. 감사합니다. 당신은 스캐너 클래스를 사용하는 경우 대신 그냥 숫자들로 당신의 라인을 분할하는 StringTokenizer를 사용하여 시도 할 수 .split()를 사용

+0

당신은 내가 당신의 제안을 사용하여 솔루션에서 일하고 있어요이 토론에 영감 http://stackoverflow.com/questions/691184/scanner-vs-stringtokenizer-vs-string-split – Adrian

답변

0

확인을 int로 배열을 변환하는 무력 방법 (I은 \ "S"버전이 작업을 수행 할 수있는 더 좋은 방법입니다 실현) 제안 :

public int[][] readFile(String fileName) throws FileNotFoundException, IOException { 
    String line = ""; 
    ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); 


    FileReader fr = new FileReader(fileName); 
    BufferedReader br = new BufferedReader(fr); 

    int r = 0, c = 0;//Read the file 
    while((line = br.readLine()) != null) { 
     Scanner scanner = new Scanner(line); 
     list.add(new ArrayList<Integer>()); 
     while(scanner.hasNext()){ 

      list.get(r).add(scanner.nextInt()); 
      c++; 
     } 
     r++; 
    } 

    //Convert the list into an int[][] 
    int[][] data = new int[list.size()][]; 
    for (int i=0;i<list.size();i++){ 
     data[i] = new int[list.get(i).size()]; 
     for(int j=0;j<list.get(i).size();j++){ 
      data[i][j] = (list.get(i).get(j)); 
     } 


    } 
    return data; 
} 
1
.split() 대신

을 사용하면 StringTokenizer를 사용하여 선을 숫자로 나눌 수 있습니다.

2

, 당신은 nextInt()을

예를 들어 전화 유지할 수 있습니다 (이 코드는 P 코드입니다. 정리해야합니다.)

scanner = new Scanner(line); 
while(scanner.hasNext()) 
    list.add(scanner.nextInt()) 
row = list.toArray() 

물론 이것은별로 최적화되지 않았습니다.

+0

을 찾을 수 있습니다 , 나는 모든 것을 정리할 때 게시 할 것입니다. – Bar

0

시도해 보았을 때 구문 분석이 제대로 작동합니다. 모두

line.split("\\s"); 

line.split(" "); 

문자열 요소의 적절한 개수로 데이터 샘플을 분할.

여기이 무엇 셀카 기반으로하는 솔루션이다 배열

int [][] intArray = new int[data.length][]; 
for (int i = 0; i < intArray.length; i++) { 
    int [] rowArray = new int [data[i].length]; 
    for (int j = 0; j < rowArray.length; j++) { 
     rowArray[j] = Integer.parseInt(data[i][j]); 
    } 
    intArray[i] = rowArray; 
} 
관련 문제