简体   繁体   中英

Swing Java GUI reading a text file with scanner

I am trying to build a GUI app, which would read a text file on the press of a button and then save contents of this file to a string. My current code, I basically tried to adapt my console code for the gui, but it doesnt seem to work. Here is my button code:

 private void convertButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              


    Scanner user_input = new Scanner(tempTextField.getText());

    String seq1 = user_input.next();

    Scanner scanner = new Scanner(new File(seq1));
    scanner.nextLine();
    String content = scanner.useDelimiter("\\Z").next();


    int N = content.length();

    textarea.append("Length of the input string is: "+N);
}

textarea = JtextArea tempTextField = JTextField

Thank you. edit: I'm using netbeans IDE

You must handle the exception from Scanner scanner = new Scanner(new File(seq1)) :

private void convertButtonActionPerformed(java.awt.event.ActionEvent evt)        
{                                              
Scanner user_input = null;
Scanner scanner = null;
try
{
user_input = new Scanner(tempTextField.getText());

String seq1 = user_input.next();


scanner = new Scanner(new File(seq1));
scanner.nextLine();
String content = scanner.useDelimiter("\\Z").next();


int N = content.length();

textarea.append("Length of the input string is: "+N);
}catch(FileNotFoundException e)
{
 e.printStackTrace();
}finally
{
 //always close scanner
 if(user_input != null)
    user_input.close();

  if(scanner  != null)
    scanner.close();



}
}

These are known as 'Checked Exceptions' . Here, the compiler would force you to handle such code in try/catch block , ie to Report the Exception, only then you can move forward for execution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM