本文介绍了在SD卡中的Andr​​oid存储数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用的文档的数据存储页面,我试着一些数据存储到SD卡。这是我的code:

  //路径写入文件
    字符串路径= Environment.getExternalStorageDirectory()。getAbsolutePath()+
                  /Android/data/"+ctxt.getString(R.string.package_name)+"/files/;
    字符串FNAME =mytest.txt;

    //外部媒体的当前状态
    串extState = Environment.getExternalStorageState();

    //外置媒体可以将其写入
    如果(extState.equals(Environment.MEDIA_MOUNTED))
    {
        尝试 {
            //确保存在的路径
            布尔存在=(新文件(路径))存在();
            如果(存在!){新的文件(路径).mkdirs(); }

            //打开输出流
            FileOutputStream中FOUT =新的FileOutputStream(路径+ FNAME);

            fOut.write(测试.getBytes());

            //关闭输出流
            fOut.flush();
            fOut.close();

        }赶上(IOException异常IOE){
            ioe.printStackTrace();
        }
 

当我创建新的FileOutputStream我得到FileNotFound异常。我也注意到,mkdirs()似乎并不创建目录。

谁能告诉我什么,我做错了什么?

我测试的一个AVD了一个2GB的SD卡和hw.sdCard:是的,DDMS的Eclipse中的文件管理器告诉我,在SD卡的唯一目录是LOST.DIR

解决方案

你有没有给你的?

您可以通过adding以下为你的的Andr​​oidManifest.xml

 <使用-权限的Andr​​oid:名称=android.permission.WRITE_EXTERNAL_STORAG​​E/>
 

Using the data-storage page in the docs, I've tried to store some data to the SD-Card.This is my code:

    // Path to write files to
    String path = Environment.getExternalStorageDirectory().getAbsolutePath() +
                  "/Android/data/"+ctxt.getString(R.string.package_name)+"/files/";
    String fname = "mytest.txt";

    // Current state of the external media
    String extState = Environment.getExternalStorageState();

    // External media can be written onto
    if (extState.equals(Environment.MEDIA_MOUNTED))
    {
        try {
            // Make sure the path exists
            boolean exists = (new File(path)).exists();
            if (!exists){ new File(path).mkdirs(); }

            // Open output stream
            FileOutputStream fOut = new FileOutputStream(path + fname);

            fOut.write("Test".getBytes());

            // Close output stream
            fOut.flush();
            fOut.close();

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

When I create the new FileOutputStream I get a FileNotFound exception. I have also noticed that "mkdirs()" does not seem to create the directory.

Can anyone tell me what I'm doing wrong?

I'm testing on an AVD with a 2GB sd card and "hw.sdCard: yes", the File Explorer of DDMS in Eclipse tells me that the only directory on the sdcard is "LOST.DIR".

解决方案

Have you given your application permission to write to the SD Card?

You do this by adding the following to your AndroidManifest.xml:

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

这篇关于在SD卡中的Andr​​oid存储数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 01:46