2014-05-24 3 views
-3

텍스트 파일의 데이터를 읽고 객체 배열에 저장하는 방법이나 예제가 필요합니다. 각 객체에는 속성 (월 이름, 숫자 및 부울 배열 [3])이 있습니다.자바 객체 배열에 텍스트 파일 읽기

May 
211345 
true false true 
June 
8868767 
false true false 

클래스 :

public class A{ 
    private String monthName; 
    private int number; 
    private boolean[] working; 

    public data() { ... } 
} 

publlic class B { 
    private A[] a; 
} 
+0

질문이 있으십니까? 아직 아무 것도 시도하지 않았습니까? –

+0

은 숙제 문제처럼 보입니다. 아무 것도 시도하는 데 많은 시간을 투자하지 않았습니다. – elToro

답변

0

다음 파일은 줄을 읽을 수있는 하나의 방법입니다

텍스트 파일이 정보 (월 이름, 숫자 및 부울 배열) 라인으로 라인을 포함 필드별로 구문 분석합니다. 이것은 데이터 파일이 올바른 것으로 가정합니다 (누락 된 필드 나 필드의 형식이 틀린 경우 등). 객체를 만들고 배열에 추가하는 코드를 추가해야합니다.

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.Arrays; 

public class ReadFile { 

    public static void main(String[] args) { 

     String fileFullPath = "C:\\Temp\\data.txt"; 

     /** verify that file exists */ 
     File checkFile = new File(fileFullPath); 
     if (!checkFile.exists()) { 
      System.err.println("error - file does not exist"); 
      System.exit(0); 
     }   

     BufferedReader br = null; 
     try { 
      br = new BufferedReader(new FileReader(fileFullPath)); 
      String line; 

      /** keep reading lines while we still have some */ 
      String month; 
      int number; 
      boolean[] barr; 

      while ((line = br.readLine()) != null) { 
       month = line; 

       line = br.readLine(); 
       number = Integer.parseInt(line); 

       line = br.readLine(); 
       String[] arr = line.split("\\s"); 
       barr = new boolean[3]; 
       for (int i=0; i < arr.length; i++) { 
        barr[i] = Boolean.parseBoolean(arr[i]); 
       } 

       /** store the fields in your object, then add to array **/ 
       System.out.println(month); 
       System.out.println(number); 
       System.out.println(Arrays.toString(barr)); 
       System.out.println(); 

      } 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (br != null) 
        br.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

    } //end main() 

} //end