2013-07-15 60 views
1

我寫了簡單的代碼將數據保存到文本文件內部。但是,在運行代碼之後,我不知道在哪裏可以找到所需的文件。此外,我在日誌中發現一條錯誤消息,因爲內部保存文件不能按預期工作

"SPAN_EXCLUSIVE_EXCLUSIVE" 

package com.example.saving_files; 

import java.io.BufferedWriter; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.OutputStream; 
import java.io.OutputStreamWriter; 
import android.os.Bundle; 
import android.app.Activity; 
import android.util.Log; 
import android.view.Menu; 

public class MainActivity extends Activity { 

    File file; 
    FileOutputStream fos; 
    String FlieName = "output.text"; 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 
      file = new File(FlieName); 
      try { 
       fos = openFileOutput(FlieName, MODE_PRIVATE); 
       fos.write(122); 
      } catch (FileNotFoundException e) { 
       Log.d("output", file.getAbsolutePath()); 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      file = getFilesDir(); 
      Log.d("output_path", file.getAbsolutePath()); 
     } 
    } 
+0

可能重複的[寫入文件到SD卡](http://stackoverflow.com/questions/2455102/writing-a-file-to-sdcard) – jww

回答

0

請檢查此代碼和註釋;

File sdcard = Environment.getExternalStorageDirectory(); 
File f = new File(sdcard, "/yourfile"); 

if (!f.exsist()) { 
    f.createNewFile(); 
    // Use outwriter here, (outputstream) search how to write into a text file in java code 
} 
+0

我更新了代碼,如圖所示,我把一個ext_sdcard放到了我的設備上。此外,我還向清單文件添加了可讀寫權限。 –

+0

請參閱上面的更新! –

+0

試試這個答案。 http://stackoverflow.com/a/11695619/1172945 – Tugrul

0
File sdCard = Environment.getExternalStorageDirectory(); 
File file = new File(sdCard, "filename"); 

FileOutputStream f = new FileOutputStream(file); 

該代碼會在您的SD的根目錄中的新文件。不要忘記添加 <uses-permission>寫入您的清單中的SD