Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

android - Copying a file from withing a apk to the internal storage

I would like to push a text document from the apk into the /system directory (Yes its a app for rooted users) and was wondering how i would do this :) My txt file is in the assests folder but it could be used if needed

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Place the text file in your project's assets directory and then extract it to the filesystem with code like the one in the following thread: How to copy files from 'assets' folder to sdcard?

EDIT: Here is some code that I use. For sourceFileName, pass in the name of the assets file relative to the assets folder (e.g. if you have myFile.txt in the assets folder, pass myFile.txt). For the destination file, pass a full path (e.g. /data/data/com.mycompany/mypackage/myFile.txt). context is the current activity (e.g. MyActivity.this).

private boolean copyFile(Context context, String sourceFileName, String destFileName)
{
    AssetManager assetManager = context.getAssets();

    File destFile = new File(destFileName);

    File destParentDir = destFile.getParentFile();
    destParentDir.mkdir();

    InputStream in = null;
    OutputStream out = null;
    try
    {
        in = assetManager.open(sourceFileName);
        out = new FileOutputStream(destFile);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1)
        {
            out.write(buffer, 0, read);
        }
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;

        return true;
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return false;
}

EDIT2: Turns out that the /system partition is mounted as read-only, even on rooted devices. This may help: Android: how to mount filesystem in RW from within my APK? (rooted, of course)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...