将数据保存到文件无法正常工作

时间:2012-05-04 03:30:39

标签: android save

我使用以下代码将密码保存在txt文件中:

String  FILE_NAME="lol.txt";
public void writeData(String password){
            FileOutputStream fOut = null;
            OutputStreamWriter osw = null;
            try{
                fOut = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
                osw = new OutputStreamWriter(fOut);
                osw.write(password);
                osw.close();
                fOut.close();
                }catch(Exception e){
                    e.printStackTrace(System.err);
                }
            }   

但是当我使用toast重新检查我刚刚保存的密码时,它显示为OK,但是当我将其登录到LogCat时,我得到了类似以下内容:

gana???????????????????????????????????? .... and more four lines.

我使用save方法将单词gana保存到我的文件中,该方法用作OnClikc方法,将EditText的值设置为密码,如下所示:

public void save(View v){
            password= txt.getText().toString();
            writeData(password);
     }

任何方式或线索如何解决这个问题?

问候

1 个答案:

答案 0 :(得分:0)

使用以下代码阅读文件

byte[] b = null;
    try 
    {
        //read file data...
        FileInputStream myFile = openFileInput("lol.txt");
        b = new byte[1024];
        myFile.read(b);
        Log.i("Pass", "File data is: " + new String(b).trim());   
        myFile.close();
    } 
    catch (IOException e) 
    {
    }

与您的代码唯一区别在于我使用new String(b).trim()删除空格。