写在外部存储在Android中的文件 [英] Write a file in external storage in Android

查看:161
本文介绍了写在外部存储在Android中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建在外部存储SD卡一个文件,并写入它。我已经通过互联网搜索和尝试,但没有得到结果,我已经添加的权限在Android的清单文件,以及,我在模拟器这样做,我我想下面的code和获得ERRR,无法创建文件。

  btnWriteSDFile =(按钮)findViewById(R.id.btnWriteSDFile);
    btnWriteSDFile.setOnClickListener(新OnClickListener(){
        //私人的ThrowableË;

        @覆盖
        公共无效的onClick(视图v){
        //从文本框SD卡上的文件数据写入
        尝试 {
        myfile文件=新的文件(/ SD卡/ mysdfile.txt);
        myFile.createNewFile();
        FileOutputStream中FOUT =新的FileOutputStream(MYFILE);
        OutputStreamWriter myOutWriter =新OutputStreamWriter(FOUT);
        myOutWriter.append(txtData.getText());
        myOutWriter.close();
        fOut.close();
        }赶上(例外五){
              Log.e(ERRR,无法创建文件,E);
        }

        } //的onClick
        }); // btnWriteSDFile
 

解决方案

您可以用这个code也可以做到这一点。

 公共类WriteSDCard延伸活动{

 私有静态最后字符串变量=MEDIA;
 私人TextView的电视;

  / **第一次创建活动时调用。 * /
@覆盖
 公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);
    电视=(TextView中)findViewById(R.id.TextView01);
    checkExternalMedia();
    writeToSDFile();
    则可与ReadRaw();
 }

/ **方法来检查是否外部媒体提供可写的。此适于从
   http://developer.android.com/guide/topics/data/data-storage.html#filesExternal * /

 私人无效checkExternalMedia(){
      布尔mExternalStorageAvailable = FALSE;
    布尔mExternalStorageWriteable = FALSE;
    字符串状态= Environment.getExternalStorageState();

    如果(Environment.MEDIA_MOUNTED.equals(州)){
        //可读写的介质
        mExternalStorageAvailable = mExternalStorageWriteable = TRUE;
    }否则,如果(Environment.MEDIA_MOUNTED_READ_ONLY.equals(州)){
        //只能读取媒体
        mExternalStorageAvailable = TRUE;
        mExternalStorageWriteable = FALSE;
    } 其他 {
        //无法读取或写入
        mExternalStorageAvailable = mExternalStorageWriteable = FALSE;
    }
    tv.append(\ñ\ nExternal媒体:可读=
            + mExternalStorageAvailable +可写=+ mExternalStorageWriteable);
}

/ **方法写入ASCII文本字符在SD卡上的文件。请注意,您必须添加
   WRITE_EXTERNAL_STORAG​​E权限清单文件或此方法将抛出
   一个FileNotFound异常,因为你不会有写权限。 * /

私人无效writeToSDFile(){

    //找到外部存储的根。
    //见http://developer.android.com/guide/topics/data/data- storage.html#filesExternal

    文件根= android.os.Environment.getExternalStorageDirectory();
    tv.append(\ nExternal文件系统的根:+根);

    //见http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder

    文件DIR =新的文件(root.getAbsolutePath()+/下载);
    dir.mkdirs();
    档案文件=新的文件(目录,myData.txt);

    尝试 {
        FileOutputStream中F =新的FileOutputStream(文件);
        PrintWriter的PW =的新PrintWriter(F);
        pw.println(你好吗);
        pw.println(你好);
        pw.flush();
        pw.close();
        f.close();
    }赶上(FileNotFoundException异常E){
        e.printStackTrace();
        Log.i(TAG,未找到*******文件。你有没有+
                添加WRITE_EXTERNAL_STORAG​​E许可清单?);
    }赶上(IOException异常E){
        e.printStackTrace();
    }
    tv.append(\ñ\ n文件写入到+文件);
}

/ **方法来读取放置在应用程序的资源/原始目录中的文本文件。该
  方法读取顺序文件中的所有行。 * /

私人无效则可与ReadRaw(){
    tv.append(\ n数据从资源读取/生/ TextFile.txt的:);
    InputStream的是= this.getResources()openRawResource(R.raw.textfile)。
    InputStreamReader的ISR =新InputStreamReader的(是);
    的BufferedReader BR =新的BufferedReader(ISR,8192); //第二arg是缓冲区大小

    //更高效(少读)执行上面是复合前pression
    / *的BufferedReader BR =新的BufferedReader(新的InputStreamReader(
            。this.getResources()openRawResource(R.raw.textfile)),8192); * /

    尝试 {
        字符串测试;
        而(真){
            测试= br.readLine();
            //的readLine()返回null如果文件中没有更多的行
            如果(测试== NULL)打破;
            tv.append(\ N++测试);
        }
        isr.close();
        is.close();
        br.close();
    }赶上(IOException异常E){
        e.printStackTrace();
    }
    tv.append(\ñ\ n该是一切);
}
}
 

I want to create a file in external storage sdCard and write to it.I have searched through internet and try but not getting the result,I have added permission in Android Manifest file as well,I am doing this on Emulator,I am trying the following code and getting a ERRR", "Could not create file".

btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
    btnWriteSDFile.setOnClickListener(new OnClickListener() {
        //private Throwable e;

        @Override
        public void onClick(View v) {
        // write on SD card file data from the text box
        try {
        File myFile = new File("/sdcard/mysdfile.txt");
        myFile.createNewFile();
        FileOutputStream fOut = new FileOutputStream(myFile);
        OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
        myOutWriter.append(txtData.getText());
        myOutWriter.close();
        fOut.close();
        } catch (Exception e) {
              Log.e("ERRR", "Could not create file",e);
        } 

        }// onClick
        }); // btnWriteSDFile

解决方案

You can do this with this code also.

 public class WriteSDCard extends Activity {

 private static final String TAG = "MEDIA";
 private TextView tv;

  /** Called when the activity is first created. */
@Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);     
    tv = (TextView) findViewById(R.id.TextView01);
    checkExternalMedia();
    writeToSDFile();
    readRaw();
 }

/** Method to check whether external media available and writable. This is adapted from
   http://developer.android.com/guide/topics/data/data-storage.html#filesExternal */

 private void checkExternalMedia(){
      boolean mExternalStorageAvailable = false;
    boolean mExternalStorageWriteable = false;
    String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // Can read and write the media
        mExternalStorageAvailable = mExternalStorageWriteable = true;
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // Can only read the media
        mExternalStorageAvailable = true;
        mExternalStorageWriteable = false;
    } else {
        // Can't read or write
        mExternalStorageAvailable = mExternalStorageWriteable = false;
    }   
    tv.append("\n\nExternal Media: readable="
            +mExternalStorageAvailable+" writable="+mExternalStorageWriteable);
}

/** Method to write ascii text characters to file on SD card. Note that you must add a 
   WRITE_EXTERNAL_STORAGE permission to the manifest file or this method will throw
   a FileNotFound Exception because you won't have write permission. */

private void writeToSDFile(){

    // Find the root of the external storage.
    // See http://developer.android.com/guide/topics/data/data-  storage.html#filesExternal

    File root = android.os.Environment.getExternalStorageDirectory(); 
    tv.append("\nExternal file system root: "+root);

    // See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder

    File dir = new File (root.getAbsolutePath() + "/download");
    dir.mkdirs();
    File file = new File(dir, "myData.txt");

    try {
        FileOutputStream f = new FileOutputStream(file);
        PrintWriter pw = new PrintWriter(f);
        pw.println("Hi , How are you");
        pw.println("Hello");
        pw.flush();
        pw.close();
        f.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.i(TAG, "******* File not found. Did you" +
                " add a WRITE_EXTERNAL_STORAGE permission to the   manifest?");
    } catch (IOException e) {
        e.printStackTrace();
    }   
    tv.append("\n\nFile written to "+file);
}

/** Method to read in a text file placed in the res/raw directory of the application. The
  method reads in all lines of the file sequentially. */

private void readRaw(){
    tv.append("\nData read from res/raw/textfile.txt:");
    InputStream is = this.getResources().openRawResource(R.raw.textfile);
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr, 8192);    // 2nd arg is buffer size

    // More efficient (less readable) implementation of above is the composite expression
    /*BufferedReader br = new BufferedReader(new InputStreamReader(
            this.getResources().openRawResource(R.raw.textfile)), 8192);*/

    try {
        String test;    
        while (true){               
            test = br.readLine();   
            // readLine() returns null if no more lines in the file
            if(test == null) break;
            tv.append("\n"+"    "+test);
        }
        isr.close();
        is.close();
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    tv.append("\n\nThat is all");
}
}

这篇关于写在外部存储在Android中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆