Android中不存在目录

时间:2015-08-06 06:40:10

标签: android file

我想在android中的文件中写入数据字符串。这就是为什么我有以下代码:

public String DumpFile(String fileName,String data)
    {
        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/saved_data");
        myDir.mkdirs();
        if(myDir.exists())
             Toast.makeText(this, "Directory exists"  ,Toast.LENGTH_LONG).show();
        else
             Toast.makeText(this, "directory not exists " ,Toast.LENGTH_LONG).show();
        //  Random generator = new Random();
        String fname = fileName;
        // showToastOnUiThread("File Name: "+fname+" and Data: "+data,
        // Toast.LENGTH_LONG);
        File file = new File(myDir, fname);
        Toast.makeText(this, "Link is "+file.getAbsolutePath(),Toast.LENGTH_LONG).show();
       // Toast.makeText(this, "Content is "+data,Toast.LENGTH_LONG).show();
        OutputStream bos = null;
        FileOutputStream out = null;
        if (file.exists())
            file.delete();
        try {
            out = new FileOutputStream(file);
            bos = new BufferedOutputStream(out);
            bos.write(data.getBytes());
            bos.flush();
            // out.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return fname; 
    } 

但是当我运行代码时,我得到了目录不存在的Toast。错误在哪里?你能帮助我吗 ?

1 个答案:

答案 0 :(得分:1)

向您的清单添加权限

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