Java 使用文件流
我想要一个程序,它可以保存您在输入对话框中输入的内容(在您单击第一个消息对话框上的“否”后),以便下次运行该程序。下次我运行程序并单击选项对话框上的“是”时,我将尝试获取文本字段,以说明用户上次输入时输入的内容。底部的代码只是出于某种原因将文本字段设置为空Java 使用文件流,java,filestream,bufferedreader,Java,Filestream,Bufferedreader,我想要一个程序,它可以保存您在输入对话框中输入的内容(在您单击第一个消息对话框上的“否”后),以便下次运行该程序。下次我运行程序并单击选项对话框上的“是”时,我将尝试获取文本字段,以说明用户上次输入时输入的内容。底部的代码只是出于某种原因将文本字段设置为空 public static String fn; public static String sn; public static int n; File f = new File("test.txt"); public void acti
public static String fn;
public static String sn;
public static int n;
File f = new File("test.txt");
public void actionPerformed (ActionEvent e){
Object[] yesNo = {"Yes",
"No",};
n = JOptionPane.showOptionDialog(null,"Would you like to use previously entered data?","Welcome Back?",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, null, yesNo,yesNo[1]);
if (n == 1){
for(fn=JOptionPane.showInputDialog("What is your first name?");!fn.matches("[a-zA-Z]+");fn.isEmpty()){
JOptionPane.showMessageDialog(null, "Alphabet characters only.");
fn=JOptionPane.showInputDialog("What is your first name?");
}
writeToFile();
for(sn=JOptionPane.showInputDialog("What is your second name?");!sn.matches("[a-zA-Z]+");sn.isEmpty()){
JOptionPane.showMessageDialog(null, "Alphabet characters only.");
sn=JOptionPane.showInputDialog("What is your second name?");
}
if (n == 0){
writeToFile();
String fullName = writeToFile();
text.setText("Welcome " + fullName + ".");
}
}
//text.setText("Welcome " + fn + " " + sn + ".");
b.setVisible(false);
b.setEnabled(false);
text.setVisible(true);
text.setBounds(140,0,220,20);
text.setHorizontalAlignment(JLabel.CENTER);
text.setEditable(false);
text.setBackground(Color.YELLOW);
pnlButton.setBackground(Color.DARK_GRAY);
}
private String writeToFile() {
String nameToWrite = fn;
OutputStream outStream = null;
String savedName = "";
try {
outStream = new FileOutputStream(f);
outStream.write(nameToWrite.getBytes());
if (n==0){
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
savedName = br.readLine();
}
if (n==1){
text.setText("Welcome " + fn + ".");
}
//text.setText("Welcome " + savedName + " " + sn + ".");
//System.out.println(savedName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != outStream) {
try {
outStream.close();
} catch (IOException e) {
// do nothing
}
}
}
return savedName;
}
每次调用
writeToFile
打开outputStream
时,它会自动覆盖文件中的内容。这意味着,当您在if
语句的开头调用writeToFile
来处理Yes选项时,您将删除以前的内容
要追加,请使用行outStream=newfileoutputstream(f,true)代码>
最好将所有的写入移动到IF块<代码> n== 1
更好的解决办法是有两种方法;一个readFromFile
和一个writeToFile
。此外,考虑使用传递给方法而不是全局变量的参数。