2017-04-08 71 views
-1

我想寫從應用程序數據庫中的文本文件中的數據,我嘗試了下面的代碼:寫入文本文件的Android

 Context context = getApplicationContext(); 

     File file = new File(context.getExternalFilesDir("routable"), "test.txt"); 



     if (!file.exists()) { 
      try { 
       file.createNewFile(); 
      } catch (Exception ex) { 
       Log.e("open file Exception", ex.getMessage().toString()); 
      } 
     } 

     try { 
      OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(file.getName(), Context.MODE_APPEND)); 
      BufferedWriter writer = new BufferedWriter(outputStreamWriter); 

      DAO dao = new DAO(getApplicationContext()); 
      Cursor res = dao.getSalePoints(); 
      res.moveToFirst(); 

      while (!res.isAfterLast()) { 

       writer.write(res.getString(0) + ", "); 
       writer.write(res.getString(1) + ", "); 
       writer.write(res.getString(2) + ", "); 
       writer.write(res.getString(3) + ", "); 

      res.moveToNext(); 
     } 



     writer.close(); 
     outputStreamWriter.close(); 

    } catch (Exception ex) { 
     Log.e("Writing file Exception", ex.getMessage().toString()); 
    } 

代碼創建的文件,它的循環拋出數據,但不寫在文件上。

  • 我在清單中添加android.permission.WRITE_EXTERNAL_STORAGE"
+0

你創建目錄'routable'? –

+0

@SimonForsberg在調用'file.createNewFile();時會自動創建;'我檢查它並且它與文件一起存在。 –

+0

'file.createNewFile();'。刪除。它的廢話。它會在外部存儲器中創建一個文件。但它不應該在那裏完成。它將由openFileOutput()完成。但是這在私人內部記憶中創造了一個。所以你現在有兩個文件。第一個是空的。第二個寫給。 – greenapps

回答

0
context.openFileOutput(file.getName(), 

更換由

new FileOutputStream(file,