如何在phonegap中使用copyto api

时间:2011-12-15 17:54:05

标签: database cordova file-copying

我想将sqlite数据库复制到数据库文件夹但不知道如何使用copyto api:

function win(entry) {
console.log("New Path: " + entry.fullPath);
}

function fail(error) {
 alert(error.code);
}

function copyFile(entry) {
 var parent = document.getElementById('parent').value,
    parentEntry = new DirectoryEntry({fullPath: parent});

 // copy the file to a new directory and rename it
 entry.copyTo(parentEntry, "file.copy", success, fail);
}

什么是入境?我必须在哪里写我的数据库路径表格资产文件夹?它是错误的,在最后一行它说成功但没有定义它?我必须写胜利吗?

2 个答案:

答案 0 :(得分:1)

File API无法访问资产目录中的文件。你需要写一个插件。

答案 1 :(得分:1)

我是通过在主要活动(java代码)中添加一些代码来实现的:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

     import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.EditText;

    public class main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String pName = this.getClass().getPackage().getName();
        try
        {
        this.copy("Databases.db","/data/data/"+pName+"/app_database/");
        }

        catch (IOException e)


    {
        e.printStackTrace();
    }

    }

    void copy(String file, String folder) throws IOException 
    {

        File CheckDirectory;
        CheckDirectory = new File(folder);
        if (!CheckDirectory.exists())
        { 
            CheckDirectory.mkdir();
        }

        InputStream in = getApplicationContext().getAssets().open(file);
        OutputStream out = new FileOutputStream(folder+file);

        // 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();

    }
    }

源:     http://gauravstomar.blogspot.com/2011/08/prepopulate-sqlite-in-phonegap.html