2012-03-31 7 views
0

그래서 다음과 같이 배열에 대한 파일 프로그램을 읽고 쓰십시오. ArrayList에 대해 다음과 같은 모양을 어떻게 나타낼까요? 구문에 문제가 있습니다. ArrayList는 다음과 같이 될 것입니다 : private ArrayList prod list = new ArrayList(); 어떻게 읽기/쓰기 IO 구문이 좋을까요? 고맙습니다.Java의 ArrayList에서 파일을 읽고 쓰는 방법

static ActionProduct[] prodlist = new ActionProduct[50]; 
    static String filename = System.getProperty("user.dir") + "\\src\\product.txt"; 
    static int pIndex=0; 


public static void readFile() throws IOException { 
     // input file must be supplied in the first argument 
     InputStream istream; 
     if (filename.length() > 0) { 
      File inputFile = new File(filename); 
      istream = new FileInputStream(inputFile); 
     } else { 
      // if no filename, use standard input stream 
      istream = System.in; 
     } 

     // use a buffered reader for line-at-a-time 
     // reading 
     BufferedReader lineReader; 
     lineReader = new BufferedReader(new InputStreamReader(istream)); 

     // read one line at a time 
     String line; 
     while ((line = lineReader.readLine()) != null) { 

      StringTokenizer tokens = new StringTokenizer(line, "\t"); 

      // String tmp = tokens.nextToken(); 
      // System.out.println("token " + tmp); 
      prodlist[pIndex] = new ActionProduct(); 
      String category = prodlist[pIndex].getCategory(); 
      category = tokens.nextToken(); 
      System.out.println("got category " +category); 

      int item = prodlist[pIndex].getItem(); 
      item = Integer.parseInt(tokens.nextToken()); 

      String name = prodlist[pIndex].getName(); 
      System.out.println("got name " +name); 

      double price = prodlist[pIndex].getPrice(); 
      price = Double.parseDouble(tokens.nextToken()); 

      int units = prodlist[pIndex].getUnits(); 
      units = Integer.parseInt(tokens.nextToken()); 
      pIndex++; 
     } 
    } 

답변

2

이 교체 :

 prodlist[pIndex] = new ActionProduct(); 

과 :

static ActionProduct[] prodlist = new ActionProduct[50]; 

다음이

static List<ActionProduct> prodlist = new ArrayList<ActionProduct>(); 

마지막으로 prodlist[pIndex]의 모든 용도를 p으로 바꾼 다음 다른 모든 곳에서 pIndex을 제거하십시오.

+0

감사합니다. Keith – ShaunK

관련 문제