2010-05-09 5 views
2

ArrayList의 단일 항목의 형식은 :Java의 텍스트 파일에서 ArrayList를 읽는 방법?

public class Account { 
    String username; 
    String password; 
} 

나는 텍스트 파일에 약간의 "계정"을 넣어 관리,하지만 지금은 내가 그들을 읽는 방법을 모른다. 이 내 ArrayList 텍스트 파일에 모습입니다 :

username1 password1 | username2 password2 | etc

이 내가 생각 해낸 코드의 일부이지만, 그것은 작동하지 않습니다.

public static void RdAc(String args[]) { 

    ArrayList<Account> peoplelist = new ArrayList<Account>(50); 

    int i,i2,i3; 
    String[] theword = null; 

    try { 

     FileReader fr = new FileReader("myfile.txt"); 
     BufferedReader br = new BufferedReader(fr); 
     String line = ""; 

     while ((line = br.readLine()) != null) { 
      String[] theline = line.split(" | "); 

      for (i = 0; i < theline.length; i++) { 
       theword = theline[i].split(" "); 
      } 

      for(i3=0;i3<theline.length;i3++) { 
       Account people = new Account(); 

       for (i2 = 0; i2 < theword.length; i2++) { 

        people.username = theword[i2]; 
        people.password = theword[i2+1]; 
        peoplelist.add(people); 
       } 
      } 

     } 
    } 
    catch (IOException ex) { 
     System.out.println("Could not read from file"); 
    } 
+1

2 일 전 거의 똑같은 질문을했습니다. http://stackoverflow.com/questions/2788080/reading-a-text-file-in-java 사례가 좀 더 복잡하지만 답변은 여전히 당신에게 유용 할 것입니다. – Jonik

+0

앞으로는 코드 서식을 신중하게 선택하십시오. 읽을 수있는 형식으로 다시 포맷해야하는 것보다 더 많은 시간이 걸렸습니다. –

+0

흠, 이런 종류의 속편처럼 보입니다. http://stackoverflow.com/questions/2777107/how-to-read-data-from-file-into-array-java – Jonik

답변

2

귀하의 질문에서 무엇이 잘못 되었습니까? 그러나, ""(theword)의 분할 결과를 포함 루프 내에서 처리하는 대신 외부에서 처리하는 것이 좋습니다.

 for (i = 0; i < theline.length; i++) { 
       theword = theline[i].split(" "); 
       Account people = new Account(); 
       for (i2 = 0; i2 < theword.length; i2++) { 
        people.username = theword[i2]; 
        people.password = theword[i2+1]; 
        peoplelist.add(people); 
       } 
      } 
+0

내가 프로그램을 실행 한 후, 내가 얻은 결과는 다음과 같습니다. "main"스레드의 예외 java.lang.ArrayIndexOutOfBoundsException : 1 이 줄에 : people.username = theword [i2]; 그리고 다시 실행하면이 줄에 다음과 같이 표시됩니다. people.password = theword [i2 + 1]; – Lox

1

무엇이 잘못 되었나요? 디버거를 밟았습니까? 그렇다면 문제의 원인이되는 부분은 무엇입니까? 내가 눈치 챘을

것 : 당신은 I2 루프해야

  1. (I2 = 0; I2 < theword.length, I2 = 2가 +) {
  2. 가 I이 설정되지 않은 것 파일에 몇 개의 항목이 있는지 모르는 경우 ArrayList의 초기 크기.
  3. 사용자 이름과 암호 사이에 공백이 있습니까?
  4. 직렬화에 대해 살펴 보셨습니까?
  5. 각 사용자 이름과 암호에 대해 줄 바꿈이 필요하지 않습니다.로드하는 것이 훨씬 쉽습니다.

    사용자 이름 1
    더 강력한 솔루션이 Matcher.group를 라인과 일치하는 정규 표현식을 정의하고 사용하는 것입니다
    USERNAME2
    암호 2

3

가 password1이 (...) 끌어 전화 들판 밖으로. 예를 들어

String s = 
Pattern p = Pattern.compile("\\s*(\\w+)\\s+(\\w+)\\s+"); 
String line; 
while ((line = br.readLine()) != null) { 
    Matcher m = p.match(line); 
    while (m.find()) { 
    String uname = m.group(1); 
    String pw = m.group(2); 
... etc ... 

형식 문제를 처리 할 때 훨씬 강력합니다. 모두 그것은 단어 쌍을 찾는다. 그 (것)들을 분리하기 위하여 무슨 끈이 사용되는지, 또는 얼마나 많은 공간이 그 사이에 있는지 상관하지 않는다.

방금 ​​정규식에서 추측했습니다. 입력의 정확한 형식에 따라 약간 조정해야 할 것입니다.

관련 문제