FileStreaming保存的文件

时间:2013-10-20 17:18:16

标签: java file bufferedreader

此部分代码无效。当用户单击n == 0时,当用户在文本字段中单击n == 1时,我正在尝试显示保存在文件中的名称。由于某些我无法想象的原因,它出来了。也许我没有正确调用savedName返回值?

    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){
        String fullName = readFromFile();
        text.setText("Welcome " + fullName + ".");
        System.out.println(fullName);
    }
    }

private void writeToFile() {

    String nameToWrite = fn;
    OutputStream outStream = null;
    //String savedName = "";
    try {
        outStream = new FileOutputStream(f);
        outStream.write(nameToWrite.getBytes());
            //BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
            //savedName = br.readLine();

            text.setText("Welcome " + fn + ".");
            //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;
}

private String readFromFile(){
    String savedName="";
    try {
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
    savedName = br.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return savedName;   
}

0 个答案:

没有答案