代码之家  ›  专栏  ›  技术社区  ›  Jack

从文本文件Javafx顺序读取

  •  0
  • Jack  · 技术社区  · 6 年前

    正在尝试按顺序读取文本文件。但是,当前,单击按钮时仅读取最后一行。我想逐一阅读文本文件中的所有问题。这是我的代码:

       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 回复  |  直到 6 年前
        1
  •  2
  •   fabian    6 年前

    要单独阅读每一行,请参考 Scanner 和电话 nextLine 每次按钮单击仅一次。然而,这使得很难确保 扫描仪 始终正确关闭。把这些行读给 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());
            }
    
        }
    });
    
        2
  •  0
  •   Asad Rehman    6 年前

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

    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());
    }