0

我想要一个程序来保存您在输入对话框中输入的内容(在您在第一个消息对话框上单击否之后),以便您下次运行该程序时使用。下次我运行程序并在选项对话框上单击“是”时,我试图让文本字段说出用户上次输入时输入的内容。底部的代码只是出于某种原因将文本字段设置为空白..

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;
}
4

1 回答 1

0

outputStream每次调用时打开时writeToFile,它都会自动覆盖文件中开始的内容。这意味着当您在语句writeToFile开头调用if以处理 Yes 选项时,您会删除以前的内容。

要追加,请使用outStream = new FileOutputStream(f, true);.

考虑将所有写入移到 if 块中可能会更好n==1

更好的解决方案是有两种方法;一个readFromFile和一个writeToFile。此外,请考虑使用传递给方法的参数而不是全局变量。

于 2013-10-20T15:49:23.977 回答