在android中创建新文件

时间:2012-08-05 20:23:40

标签: android file ringtone setting

我有一个问题,我想在我的主要活动中设置一个铃声,我读了这个教程:http://androidgenuine.com/?tag=set-as-ringtone-android,但是功能保存不起作用,更具体我无法创建文件,功能是假的。我再次写了一个创建新文件的部分,但即使这部分也不起作用,这里是代码,什么是错的(它; s返回false而非文件被创建)?

    public boolean save2(int ressound){

    String path="/sdcard/sounds/";
    String filename="ring.mp3";
    byte[] buffer = null;
    FileOutputStream save;
    InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
    int size=0;
    try {
        size=fIn.available();
        buffer = new byte[size];
        fIn.read(buffer);
        fIn.close();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        save = new FileOutputStream(path+filename);
        save.write(buffer);
        save.flush();
        save.close();
        return true;
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
}

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

我只能猜测您指定的目录可能不存在,或者您的清单中没有相应的权限集。

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

您应该使用

中的文档中的以下内容构建它

http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory()

File path = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");

// Make sure the Pictures directory exists.
path.mkdirs();

您还必须检查外部存储器是否已安装。

String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        mExternalStorageAvailable = mExternalStorageWriteable = true;
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        mExternalStorageAvailable = true;
        mExternalStorageWriteable = false;
    } else {
        mExternalStorageAvailable = mExternalStorageWriteable = false;
    }