[英]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.