[英]Scanner doesn't read from file
我正在编写程序,该程序将读取文件,由用户选择。 我有代码:
public class program extends javax.swing.JFrame {
private String textEncode;
...
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fch = new JFileChooser();
int choose = fch.showOpenDialog(this);
if(choose == JFileChooser.APPROVE_OPTION) {
String help = fch.getSelectedFile().getPath();
jTextField2.setText(help);
try {
Scanner in = new Scanner(new File(help));
while(in.hasNextLine()) {
textEncode = in.nextLine();
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(this, "Nie znaleziono pliku", "Błąd wczytywania", JOptionPane.ERROR_MESSAGE);
}
}
jTextArea1.setText(textEncode);
System.out.println(textEncode);
}
我的文件有1行文字。 当程序结束读取文件时,变量textEncode的值为“ null”。 问题在哪里? 我尝试使用in.hasNext()
in.next()
和in.hasNext()
,但是它也不起作用。
我找到了解决方案:
public class program extends javax.swing.JFrame {
private String textEncode;
...
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fch = new JFileChooser();
int choose = fch.showOpenDialog(this);
if(choose == JFileChooser.APPROVE_OPTION) {
String help = fch.getSelectedFile().getPath();
jTextField2.setText(help);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(help), "UTF-8"));
String line;
String readed = "";
while((line = in.readLine()) != null) {
readed = readed + line + "\n";
}
jTextArea1.setText(readed);
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(this, "Nie znaleziono pliku", "Błąd wczytywania", JOptionPane.ERROR_MESSAGE);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(aes.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(aes.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
但是现在我在显示jTextArea1时遇到问题。 加载文件后,将调整textArea的大小,如下所示:将应用程序窗口 TextArea添加到jScrollPane中。
我遇到了同样的问题,花了我一段时间才解决。
我的问题是我的文件包含法语特殊字符,例如“é”。 这导致扫描程序为scanner.nextLine()返回“ null”,而不会引起任何异常,无论文件有多长时间,无论特殊字符放在何处。
为了解决这个问题, 我删除了所有特殊字符。 如果有人有办法让Scanner读取特殊字符,欢迎在下面发表评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.