使用文件流

时间:2013-10-20 15:33:01

标签: java filestream bufferedreader

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

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

1 个答案:

答案 0 :(得分:0)

每次拨打outputStream时打开writeToFile,它会自动覆盖文件中的内容。这意味着当您在writeToFile语句的开头调用if来处理“是”选项时,将删除之前的内容。

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

最好考虑将ALL写入if块n==1

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