从文本文件Javafx顺序读取

时间:2018-04-06 16:02:17

标签: java javafx javafx-8

尝试从文本文件中顺序读取。但是,目前,单击按钮时只读取最后一行。我想一个接一个地阅读文本文件中的所有问题。这是我的代码:

   buttonNext.setOnAction(new EventHandler<ActionEvent>(){
    public void handle(ActionEvent E){

       java.io.File inFile = new java.io.File("QuestionSheet.txt");


       try {
           java.util.Scanner input = new java.util.Scanner(inFile);

            while (input.hasNext()){
                String[] lineOfCsv = input.nextLine().split(",");
                questionLabel.setText(lineOfCsv[0]);
                aRadio.setText(lineOfCsv[1]);
                bRadio.setText(lineOfCsv[2]);
                cRadio.setText(lineOfCsv[3]);
                dRadio.setText(lineOfCsv[4]);


            }

        } catch (java.io.IOException ex){
        System.out.println("Error reading file " + ex.toString());
        }

       buttonNext.setText("Next Question");

    }
    });

2 个答案:

答案 0 :(得分:2)

要单独读取每一行,请保留对Scanner的引用,并且每按一次按钮只调用nextLine一次。但是,这使得很难确保Scanner始终正确关闭。读取List<String>的行并反复遍历它可能更简单:

Path filePath = Paths.get("QuestionSheet.txt");
List<String> lines = Files.readAllLines(filePath); // using nio for simplicity here

buttonNext.setOnAction(new EventHandler<ActionEvent>(){

    // iterator for stepwise iterating through the list
    private final Iterator<String> iterator = lines.iterator();

    @Override
    public void handle(ActionEvent event){
        if (iterator.hasNext()) {
            String[] lineOfCsv = iterator.next().split(",");
            questionLabel.setText(lineOfCsv[0]);
            aRadio.setText(lineOfCsv[1]);
            bRadio.setText(lineOfCsv[2]);
            cRadio.setText(lineOfCsv[3]);
            dRadio.setText(lineOfCsv[4]);
            buttonNext.setDisable(!iterator.hasNext());
        }

    }
});

答案 1 :(得分:0)

使用缓冲读取器和输入流逐行读取,原因是缓冲读取器包含默认的读取线功能。这很有帮助。

buttonNext.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent E){
try{
FileInputStream fstream = new FileInputStream("QuestionSheet.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)   {
  System.out.println (strLine);
  String[] lineOfCsv = strLine.split(",");
  questionLabel.setText(lineOfCsv[0]);
  aRadio.setText(lineOfCsv[1]);
  bRadio.setText(lineOfCsv[2]);
  cRadio.setText(lineOfCsv[3]);
  dRadio.setText(lineOfCsv[4]);
}
in.close();
}catch (Exception e){
  System.err.println("Error: " + e.getMessage());
}