2015-03-08 79 views
0

我正在制作应用程序,它将使用文本文件来存储密码。我目前正试图将该密码保存到该文件,它看起来像保存但我不知道,因为我无法从文件中读取。使用openFileOutput从文本文件读取/写入

直接尝试将密码保存到文件后,我试图在文本内容中显示文件的内容,它们用于输入字符串(这只是为了测试它是否保存),但没有出现。

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

回答

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); 
} 
+0

行fos.write(txtEditor.getText()。toString()); 无法解析方法'write(java.lang.String)。 – user3343264 2015-03-08 22:34:29

+0

Woops。检查更新它实际上需要一个字节[] – 2015-03-08 22:37:11

+0

它现在显示在文本字段,所以它看起来像它的工作,非常感谢 – user3343264 2015-03-08 22:39:40