将文件从资产复制到SD卡

时间:2013-03-20 10:03:02

标签: android android-assets

我是开发Android应用的新手。关于我的问题,我发现了以下帖子,但我不确定如何将其实现到我现有的项目中。 How to copy files from 'assets' folder to sdcard?

我想将它实现到ZhuangDict,这是一个能够读取Stardict文件的字典应用程序。 http://code.google.com/p/zhuang-dict/source/browse/trunk/ZhuangDict/src/cn/wangdazhuang/zdict/ZhuangDictActivity.java

ZhuanDict在第一次启动时创建一个名为“zdict”的空目录。 我想做的是将我自己的stardict文件从asset复制到zdict目录。

我对编程知之甚少。如果您能为我提供一步一步的指南,请查看Google代码中的ZhuangDict源代码,我将不胜感激。

2 个答案:

答案 0 :(得分:0)

检查出来

private static String DB_PATH = "/data/data/com.packagename.myapp/databases/";

   try {
        // Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(
                "dbname.sqlite");
        // Path to the just created empty db
        String outFileName = DB_PATH + DATABASE_NAME;

        // Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        // transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[myInput.available()];
        int read;
        while ((read = myInput.read(buffer)) != -1) {
            myOutput.write(buffer, 0, read);
        }

        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    } catch (IOException e) {
        Log.e(TAG, "copyDataBase Error : " + e.getMessage());
    }

答案 1 :(得分:0)

您还可以将文件放在原始资源(/ res / raw)文件夹中并使用此标准函数:

protected void CopyResource(int aInputIDResource, String aOutputFileName, boolean afForceWrite) {
        if (afForceWrite == false) {
            InputStream theTestExist;
            try {
                theTestExist = openFileInput(aOutputFileName);
                theTestExist.close();
                return;
            } catch (IOException e) {
            }
        }

        char[] theBuffer = new char[1024];
        int theLength;

        try {
            OutputStreamWriter out = new OutputStreamWriter(openFileOutput(
                    aOutputFileName, MODE_WORLD_READABLE), "ISO-8859-1");
            InputStreamReader in = new InputStreamReader(getResources()
                    .openRawResource(aInputIDResource), "ISO-8859-1");

            while ((theLength = in.read(theBuffer)) > 0)
                out.write(theBuffer, 0, theLength);

            out.flush();
            out.close();
        } catch (Exception e) {
            Log.e("TAG", "Error: " + e.getMessage());
        }
    }

然后在您的应用程序或活动的onCreate()函数中,调用:

CopyResource(R.raw.your_database, "MR_SBusPlugin.so", false);