简体   繁体   English

Swing Java GUI使用扫描仪读取文本文件

[英]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. 我正在尝试构建一个GUI应用程序,它将按一下按钮即可读取文本文件,然后将该文件的内容保存到字符串中。 My current code, I basically tried to adapt my console code for the gui, but it doesnt seem to work. 我当前的代码,我基本上试图使我的控制台代码适应gui,但是它似乎不起作用。 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 textarea = JtextArea tempTextField = JTextField

Thank you. 谢谢。 edit: I'm using netbeans IDE 编辑:我正在使用netbeans IDE

You must handle the exception from Scanner scanner = new Scanner(new File(seq1)) : 您必须通过以下方式处理异常: 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. 在这里,编译器将迫使您在try / catch块中 处理 此类代码 ,即要报告异常,只有这样您才能继续执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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