簡體   English   中英

android將文件從資產復制到sd卡

[英]android copy file from assets to sd card

這是MyNewMain.java

        CopyAssets();


    private void CopyAssets() {
        AssetManager assetManager = getAssets();
        String[] files = null;
        try {
            files = assetManager.list("Files");
        } catch (IOException e) {
            Log.e("tag", e.getMessage());
        }

        for(String filename : files) {
            System.out.println("File name => "+filename);
            InputStream in = null;
            OutputStream out = null;
            try {
                in = assetManager.open("Files/"+filename);
                out = new FileOutputStream(Environment.getExternalStorageDirectory().toString() +"/" + filename);
                copyFile(in, out);
                in.close();
                in = null;
                out.flush();
                out.close();
                out = null;
            } catch(Exception e) {
                Log.e("tag", e.getMessage());
            }
        }
    }
    private void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while((read = in.read(buffer)) != -1){
            out.write(buffer, 0, read);
        }
    }

在我的資產文件夾中,我有一個名為“文件”的文件夾。 我正在調用CopyAssets()的onCreate方法中有.txt文件;

較低的是我使用的方法。

問題在於這無能為力。 我絕對不知道為什么我的文件沒有被復制。 在我的清單中,我已添加

和app.iml包含

我知道已經解決了這個問題,但是我有一種更為優雅的方法可以從資產目錄復制到sdcard上的文件。 它不需要“ for”循環,而是使用文件流和通道來完成工作。

(注意)如果使用任何類型的壓縮文件,如APK,PDF,...,則可能需要先重命名文件擴展名,然后再插入資產中,然后將其復制到SD卡后再重命名)

AssetManager am = context.getAssets();
AssetFileDescriptor afd = null;
try {
    afd = am.openFd( "MyFile.dat");

    // Create new file to copy into.
    File file = new File(Environment.getExternalStorageDirectory() + java.io.File.separator + "NewFile.dat");
    file.createNewFile();

    copyFdToFile(afd.getFileDescriptor(), file);

} catch (IOException e) {
    e.printStackTrace();
}

一種無需循環即可復制文件的方法。

public static void copyFdToFile(FileDescriptor src, File dst) throws IOException {
    FileChannel inChannel = new FileInputStream(src).getChannel();
    FileChannel outChannel = new FileOutputStream(dst).getChannel();
    try {
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        if (inChannel != null)
            inChannel.close();
        if (outChannel != null)
            outChannel.close();
    }
}

感謝JPM的回答

在android api 22上,對AssetFileDescriptor對象調用getFileDescriptor()將返回整個apk文件的FileDescriptor。 所以@Salmaan的答案在android api 22上是錯誤的。

我沒有在其他api中看到源代碼。 所以我不知道其他api中getFileDescriptor()的行為。

我找到了這個問題的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM