2012-02-03 2 views
1

제목에 설명 된대로 각 줄을 문자열에 할당하려고합니다 (궁극적 인 목표는 텍스트 파일에서 한 줄을 당긴 다음 사용하는 것입니다. 답은 아래의 줄을 입력 한 다음 파일이 끝날 때까지이 작업을 반복하십시오.) 이제는 전체 파일을 문자열 (줄)에 할당해야합니다. 다른 수입을 사용스캐너를 통해 문자열에 txt 파일의 한 줄 지정

import java.io.*; 
import java.util.Scanner; 
import java.lang.*; 
import javax.swing.JOptionPane; 

public class Test { 

public static void main(String[] args) { 

    // Location of file to read 
    File file = new File("a.txt"); 

    try { 

     Scanner scanner = new Scanner(file); 

     while (scanner.hasNextLine()) { 
      String line = scanner.nextLine(); 
      JOptionPane.showInputDialog("" + line); 
     } 
     scanner.close(); 
    } catch (FileNotFoundException e) { 
    System.out.println("Can't find file"); 
    } 

} 
} 

감사 어떤 도움이나 해결 방법 - - 덕분에 여기 내 코드입니다.

답변

1

당신은 선이 파일에서 읽을 저장 StringArrayList을 사용할 수 있습니다 : 당신이 각 라인을 저장하려면 당신은 문자열의 ArrayList를에 넣어 수 lines은 파일에 표시된 순서대로 파일의 행을 포함하므로 lines 배열을 반복 할 수 있으며 lines.get(i)이 질문이되고 lines.get(i+1)이 대답이됩니다.

for (int i = 1; i < lines.size(); i+=2) 
{ 
    String question = lines.get(i - 1); 
    String answer = lines.get(i); 
    JOptionPane.showInputDialog("Question: " + question + " Answer:" + answer); 
} 
0

이제 실행되면서 라인 변수는 실행이 끝날 때 파일의 마지막 줄만 포함합니다.

public static void main(String[] args) { 

    // Location of file to read 
    File file = new File("a.txt"); 
    List<String> lines = new ArrayList<String>(); 

    try { 

     Scanner scanner = new Scanner(file); 

     while (scanner.hasNextLine()) { 
      lines.add(scanner.nextLine(); 
     } 
     scanner.close(); 
    } catch (FileNotFoundException e) { 
    System.out.println("Can't find file"); 
    } 
} 

배열 목록 :

ArrayList<String> lines = new ArrayList<String>(); 
.... 
while (scanner.hasNextLine()) { 
    String line = scanner.nextLine(); 
    lines.add(line); 
    JOptionPane.showInputDialog("" + line); 
}