2017-05-27 147 views
0

我是Android編程的初學者。 我想提供一個窗體給用戶輸入一些信息。 我想將該信息寫入文件,然後從文件中讀取並在TextView中顯示。目前,我讀到的是null。你能幫我解決這個問題嗎? 的代碼是這一個:Android - 從文件讀取和寫入

submit.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     // write 
     StringBuilder s = new StringBuilder(); 
     s.append("Event name: " + editText1.getText() + "|"); 
     s.append("Date: " + editText2.getText() + "|"); 
     s.append("Details: " + editText3.getText() + "|"); 

     String extStorageDirectory = Environment.getExternalStorageDirectory().toString(); 
     File file= new File(extStorageDirectory, "config.txt"); 
     try { 
      writeToFile(s.toString().getBytes(), file); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     // read from file and show in text view 
     Context context = getApplicationContext(); 
     String filename = "config.txt"; 
     String str = readFromFile(context, filename); 
     String first = "You have inputted: \n"; 
     first += str; 
     textView.setText(first); 

    } 
}); 

寫功能:

public static void writeToFile(byte[] data, File file) throws IOException { 
    BufferedOutputStream bos = null; 
    try { 
     FileOutputStream fos = new FileOutputStream(file); 
     bos = new BufferedOutputStream(fos); 
     bos.write(data); 
    } 
    finally { 
     if (bos != null) { 
      try { 
       bos.flush(); 
       bos.close(); 
      } 
      catch (Exception e) { 
      } 
     } 
    } 
} 

讀取功能:

public String readFromFile(Context context, String filename) { 
    try { 
     FileInputStream fis = context.openFileInput(filename); 
     InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); 
     BufferedReader bufferedReader = new BufferedReader(isr); 
     StringBuilder sb = new StringBuilder(); 
     String line; 
     while ((line = bufferedReader.readLine()) != null) { 
      sb.append(line).append("\n"); 
     } 
     return sb.toString(); 
    } catch (FileNotFoundException e) { 
     return ""; 
    } catch (UnsupportedEncodingException e) { 
     return ""; 
    } catch (IOException e) { 
     return ""; 
    } 
} 
+0

您確定您使用正確的文件路徑嗎? –

+0

如果我沒有,我會有一個錯誤。但我沒有錯誤也沒有警告 –

回答

0

EDITTEXT的getText()方法返回editable。所以首先你應該使用toString()函數將它轉換爲字符串。還要檢查你是否給了WRITE_EXTERNAL_STORAGE權限。

+1

謝謝你的回答! –

0

如果我不想你寫入文件

String extStorageDirectory = 
Environment.getExternalStorageDirectory().toString(); 
File file= new File(extStorageDirectory, "config.txt"); 
東西

但你讀過從

FileInputStream fis = context.openFileInput(filename); 

後者在應用程序基目錄中使用了一個dir,而輸出則轉到了外部strage目錄的基本目錄。

爲什麼不使用context.openFileOutput()代替getExternalStorageDirectory()

如果該文件應該被存儲在外部,嘗試如下:您創建File對象的方式保持不變。請用FileInputStream代替FileOutputStream fos = new FileOutputStream(file);(寫作)。請記住在清單中設置適當的權限。在什麼條件下他們是必要的,請參閱Android文檔。

+0

我怎麼才能從外部存儲讀取? –

+0

我已經設法使用內部存儲。謝謝托馬斯! –

+0

很高興如果我能夠幫助 – Thomas