2012-10-16 66 views
-2

我創建使用此代碼的data.txt:讀取文件的Android

String data = "etc etc etc etc。。" 
        try { 
        FileOutputStream fOut; 

        fOut = openFileOutput("data.txt", MODE_WORLD_READABLE); 

        OutputStreamWriter fw = new OutputStreamWriter(fOut); 

        fw.write(data); 
        fw.flush(); 
        fw.close(); 

       } catch (IOException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 

,但我怎麼知道它被寫進?我如何爲我的data.txt定義路徑?

我想用其他活動來讀它,所以我需要知道如何從路徑以及閱讀..

+1

這是標準的Java文件IO。谷歌可以指向你一千個教程 –

+0

我整天都試過,它不工作! –

+0

你應該使用['Environment.getDataDirectory()'](http://developer.android.com/reference/android/os/Environment.html)並在那裏創建一個文件。 –

回答

0

你可以做到這樣......

 static final String FILE_LOG = "log.txt"; 

    String s = "Hello"; 
      File file; 
      FileOutputStream fos = null; 

      try 
      { 
       file = new File(getExternalFilesDir(null), FILE_LOG); 
       fos = new FileOutputStream(file); 
      } 
      catch(FileNotFoundException e) 
      { 
       Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show(); 
       return; 
      } 

      try 
      { 
       fos.write(s.getBytes()); 
       fos.close(); 
      } 
      catch(IOException e) 
      { 
       Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show(); 
       return; 
      } 

    String path = file.getAbsolutePath().toString(); 
    Toast.makeText(this, "File is saved to " + path, Toast.LENGTH_SHORT).show(); 
    Log.e("PATH", path); 

希望這將有助於您。

謝謝...

-1

我認爲這將工作:

File root = Environment.getExternalStorageDirectory(); 
String data = "etc etc etc etc。。"; 
try{ 
    if (root.canWrite()){ 
     File txtfile = new File(root, "data.txt"); 
     FileWriter txtwriter = new FileWriter(txtfile, true); 
     BufferedWriter out = new BufferedWriter(txtwriter); 
     out.write(data); 
     out.close(); 
    } 
} 
catch (IOException e){ 
    e.printStackTrace(); 
} 

}

此代碼將創建的data.txt文件到外部存儲的根目錄。不要忘了將這個許可添加到您的AndroidManifest.xml文件中:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>