Java 为什么';我的代码不能打印出txt文件的所有行吗?
因此,我有一段代码,它应该从“Questions.txt”中读回文本,并显示在JTextArea中,带有保存任何编辑的选项,但它只读回最后一行。怎么了Java 为什么';我的代码不能打印出txt文件的所有行吗?,java,Java,因此,我有一段代码,它应该从“Questions.txt”中读回文本,并显示在JTextArea中,带有保存任何编辑的选项,但它只读回最后一行。怎么了 package secondgui; public class MainGUI { public static void main (String [] args) { SecondGUI phillip = new SecondGUI(); phillip.repaint(); } } package secon
package secondgui;
public class MainGUI {
public static void main (String [] args) {
SecondGUI phillip = new SecondGUI();
phillip.repaint();
}
}
package secondgui;
import java.awt.event.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public class SecondGUI extends JFrame implements ActionListener {
/**
* @param args the command line arguments
*/
private JButton save = new JButton("Save Edits");
private JTextArea edit = new JTextArea();
public SecondGUI() {
this.setVisible(true);
this.setSize(600, 600);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
this.add(panel);
JLabel label = new JLabel("Please edit the question(s) below"
+ " as you see fit");
panel.add(save);
save.addActionListener(this);
panel.add(label);
edit.setLineWrap(true);
try {
Scanner b = new readFile().openFile();
while (b.hasNextLine()) {
edit.setText(b.nextLine() + "\n");
}
} catch (Exception e) {}
JScrollPane scrollyBar = new JScrollPane(edit);
scrollyBar.setBounds(150, 150, 250, 100);
scrollyBar.setSize(300, 300);
panel.add(scrollyBar);
this.repaint();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == save) {
PrintWriter out;
FileWriter outFile;
try {
outFile = new FileWriter("Questions.txt");
out = new PrintWriter(outFile);
out.println(edit.getText());
out.close();
outFile.close();
} catch (IOException ex) {
Logger.getLogger(SecondGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
package secondgui;
import java.io.*;
import java.util.*;
public class readFile {
private Scanner x = new Scanner(System.in);
public Scanner openFile() {
try {
x = new Scanner(new File("Questions.txt"));
} catch (Exception e) {
System.out.println("Could not find file");
}
return x;
}
public void readFile() {
while (x.hasNext()) {
x.next();
}
}
public void closeFile() {
x.close();
}
}
有问题的行是:
edit.setText(b.nextLine()+“\n”)代码>应该追加下一行,而不是设置文本。如果我没记错的话,可以使用一个edit.append()
方法
查看以了解有关JTextArea
的更多信息,无论最后一行是什么问题,我认为您的readfile()
机制充其量是有问题的。这:
private Scanner x = new Scanner(System.in);
try {
x = new Scanner(new File("Questions.txt"));
} catch (Exception e) {
System.out.println("Could not find file");
}
看起来很狡猾。如果遇到错误,扫描仪默认为标准输入。这是:
public void readFile() {
while (x.hasNext()) {
x.next();
}
}
似乎只是在不做任何事情的情况下对文件进行迭代。我会阅读,并且(至少目前)如果其中任何一个失败,就会抛出显式异常。方法将覆盖任何以前设置的文本。你为什么不在上面加上文字呢?