Java搜索文件

时间:2017-04-25 03:44:51

标签: java file io save stringbuilder

我有2个字符串变量:

"的 givenAccnt "是从用户

获得的输入字符串

"的 accntToken "是一行文本

的子字符串(第一个字符串)

如果givenAccnt 等于 accntToken,我想返回与accntToken匹配的文本行

此外,可能存在多于1个匹配的情况。我想将所有匹配保存到变量中,然后立即返回这些匹配(行)。

以下代码仅返回最后一行的匹配项。 (如果匹配在其他行中则会错过它)

我似乎无法理解为什么它会这样。

任何帮助都将不胜感激。

givenAccnt = searchTextField.getText();//else, user is using search field to get given account
try
   {
      scanner = new Scanner(file);        //initialize scanner on file
      while(scanner.hasNextLine())        //while lines are being scanned
      {   
         getLine = scanner.nextLine();          //gets a line
         int i = getLine.indexOf(' ');          //get first string-aka-accnToken
         accntToken = getLine.substring(0, i);    
       }
       if(givenAccnt.equals(accntToken))   //if match   
       {
          collectedLines = new StringBuilder().append(getLine).toString();
          psswrdLabels = new JLabel(collectedLines, JLabel.LEFT);
          psswrdLabels.setAlignmentX(0);
          psswrdLabels.setAlignmentY(0);
          fndPwrdsCNTR += 1;     //counter for number of passwords found 
          JOptionPane.showMessageDialog(null, psswrdLabels ,+fndPwrdsCNTR+" PASSWORD(S) FOUND!", JOptionPane.INFORMATION_MESSAGE);    //shows window with matched passwords (as JLabels)
                            searchTextField.setText("");    //clears search field, if it was used
         }else
           //..nothing found
     }catch (FileNotFoundException ex) {
         //..problem processing file...
                    } 

1 个答案:

答案 0 :(得分:0)

您无法在每一行上创建新的StringBuilder。而是在阅读线之前创建它。代码:

givenAccnt = searchTextField.getText();//else, user is using search field to get given account
try
   {
builder=new StringBuilder();//initialize builder to store matched lines
      scanner = new Scanner(file);        //initialize scanner on file
      while(scanner.hasNextLine())        //while lines are being scanned
      {   
         getLine = scanner.nextLine();          //gets a line
         int i = getLine.indexOf(' ');          //get first string-aka-accnToken
         accntToken = getLine.substring(0, i);    
       }
       if(givenAccnt.equals(accntToken))   //if match   
       {
          collectedLines = builder.append(getLine).toString();
          psswrdLabels = new JLabel(collectedLines, JLabel.LEFT);
          psswrdLabels.setAlignmentX(0);
          psswrdLabels.setAlignmentY(0);
          fndPwrdsCNTR += 1;     //counter for number of passwords found 
          JOptionPane.showMessageDialog(null, psswrdLabels ,+fndPwrdsCNTR+" PASSWORD(S) FOUND!", JOptionPane.INFORMATION_MESSAGE);    //shows window with matched passwords (as JLabels)
                            searchTextField.setText("");    //clears search field, if it was used
         }else
           //..nothing found
     }catch (FileNotFoundException ex) {
         //..problem processing file...
                    }