将文件复制到外部sdcard android

时间:2013-02-18 13:26:20

标签: android cordova

我无法将文件复制到外部SD卡。不显示任何错误,实际上显示成功,但文件不在SD卡上。代码如下:

window.resolveLocalFileSystemURI(fileURI, step1,fail);

function step1(tmp_file)
{
       file = tmp_file;
       window.resolveLocalFileSystemURI("file:///mnt/extsd", step2,fail); //resolve destinaion
}

function step2(destination)
{
        file.moveTo(destination,"example.jpg",move_success, move_fail);
}

所以最后它调用了move_success。

注意:如果我将“file:/// mnt / extsd”中的路径更改为内部sdcard路径'file:/// mnt / sdcard'

清单中的权限

<uses-permission android:name="android.permission.CAMERA" />
        <uses-permission android:name="android.permission.VIBRATE" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
        <uses-permission android:name="android.permission.READ_PHONE_STATE" />
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.RECEIVE_SMS" />
        <uses-permission android:name="android.permission.RECORD_AUDIO" />
        <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
        <uses-permission android:name="android.permission.READ_CONTACTS" />
        <uses-permission android:name="android.permission.WRITE_CONTACTS" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

1 个答案:

答案 0 :(得分:0)

你应该建立你的路径,而不是将其定义为默认路由,因为不是在所有设备中sdcard被称为“sdcard”,例如,我有一个chinnese平板电脑,这有2个SD卡插槽,所以我必须使用路径“sdcard2”你可以做到:

File sdcard = Environment.getExternalStorageDirectory();
String path = "file://"+sdcard.getAbsolutePath();

然后你可以使用变量

window.resolveLocalFileSystemURI(path, step2,fail); //resolve destinaio

或者,您可以使用此方法复制文件:

public void copy(File src, File dst) throws IOException {
    try {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst);

        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    } catch (IOException io) {
        Toast.makeText(this, "Error: " + io, Toast.LENGTH_LONG).show();
    }
}

您可以复制该文件,然后将其删除,作为快速移动。

或者作为其他选择,您可以使用文件的属性renameTo(), 例如:

File sdcard = Environment.getExternalStorageDirectory();
File example= new File(sdcard.getAbsolutePath()+"/example.txt");
File newpath= new File(sdcard.getAbsolutePath()+"/examplefolder/example.txt");
example.renameTo(newpath);//this will move the file to the new path