2015-03-08 60 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

相關問題