使用openFileOutput从文本文件读/写

时间:2015-03-08 21:56:12

标签: android android-file

我正在创建一个应用程序,它将使用文本文件来存储密码。我目前正在尝试将此密码保存到文件中,它看起来像是保存但我无法知道因为我无法从文件中读取。

在我尝试将密码保存到文件后,我试图在他们用来输入字符串的同一文本字段中显示文件的内容(这只是为了测试它是否已保存)但没有出现。< / p>

    public class setPin extends ActionBarActivity {


private final static String STORETEXT = "storetext.txt";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_set_pin);

}

public void buttonClick(View v) {
    EditText txtEditor=(EditText)findViewById(R.id.editText);
    try {
        FileOutputStream fos = openFileOutput(STORETEXT,         Context.MODE_PRIVATE);
        Writer out = new OutputStreamWriter(fos);
        out.write(txtEditor.getText().toString());
        txtEditor.setText("");
        fos.close();

        Toast.makeText(this, "Saved password", Toast.LENGTH_LONG).show();
        }

    catch (Throwable t) {
        Toast.makeText(this, "Exception: " + t.toString(),    Toast.LENGTH_LONG).show();
       }

 //HERE I TRY TO PRINT THE SAVED STRING INTO THE TEXTFIELD

    try {
        BufferedReader inputReader = new BufferedReader(new InputStreamReader(
                openFileInput(STORETEXT)));
        String inputString;
        StringBuffer stringBuffer = new StringBuffer();
        while ((inputString = inputReader.readLine()) != null) {
            stringBuffer.append(inputString + "\n");
        }
        txtEditor.setText(stringBuffer.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
 }

1 个答案:

答案 0 :(得分:0)

尝试这样的事情。

public void buttonClick(View v) {
    EditText txtEditor = (EditText) findViewById(R.id.editText);
    try {
        FileOutputStream fos = openFileOutput(STORETEXT, Context.MODE_PRIVATE);
        fos.write(txtEditor.getText().toString().getBytes());
        txtEditor.setText("");
        fos.close();

        Toast.makeText(this, "Saved password", Toast.LENGTH_LONG).show();
    }

    catch (Throwable t) {
        Toast.makeText(this, "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
    }

    String contents = "";
    try {
        FileInputStream fin = openFileInput(STORETEXT);
        int i;
        while ((i = fin.read()) != -1) {
            contents = contents + Character.toString((char) i);
        }
    }
    catch (IOException e) {
    }
    txtEditor.setText(contents);
}