【Android】复制assets里的单文件到指定文件夹

版权声明:本文为博主原创文章,商业转载请联系博主获得授权,非商业转载请注明出处,否则追究其法律责任。 https://blog.csdn.net/u013642500/article/details/80069811

转载请注明出处,原文链接:https://blog.csdn.net/u013642500/article/details/80069811


本方法使用前提是已拥有权限,未对权限不足情况进行处理,如有需要可自行添加。

关于读写权限的总结请参考:https://blog.csdn.net/u010784887/article/details/53560025

    /**
     * 复制单个文件
     *
     * @param outPath String 输出文件路径 如:data/user/0/com.test/files
     * @param fileName String 要复制的文件名 如:abc.txt
     * @return <code>true</code> if and only if the file was copied; <code>false</code> otherwise
     */
    private boolean copyAssetsSingleFile(String outPath, String fileName) {
        File file = new File(outPath);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                Log.e("--Method--", "copyAssetsSingleFile: cannot create directory.");
                return false;
            }
        }
        try {
            InputStream inputStream = getAssets().open(fileName);
            File outFile = new File(file, fileName);
            FileOutputStream fileOutputStream = new FileOutputStream(outFile);
            // Transfer bytes from inputStream to fileOutputStream
            byte[] buffer = new byte[1024];
            int byteRead;
            while (-1 != (byteRead = inputStream.read(buffer))) {
                fileOutputStream.write(buffer, 0, byteRead);
            }
            inputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

/**
 * 复制单个文件
 *
 * @param outPath String 输出文件路径 如:data/user/0/com.test/files
 * @param fileName String 要复制的文件名 如:abc.txt
 * @return <code>true</code> if and only if the file was copied; <code>false</code> otherwise
 */
private boolean copyAssetsSingleFile(String outPath, String fileName) {
    File file = new File(outPath);
    if (!file.exists()) {
        if (!file.mkdirs()) {
            Log.e("--Method--", "copyAssetsSingleFile: cannot create directory.");
            return false;
        }
    }
    try {
        InputStream inputStream = getAssets().open(fileName);
        File outFile = new File(file, fileName);
        FileOutputStream fileOutputStream = new FileOutputStream(outFile);
        // Transfer bytes from inputStream to fileOutputStream
        byte[] buffer = new byte[1024];
        int byteRead;
        while (-1 != (byteRead = inputStream.read(buffer))) {
            fileOutputStream.write(buffer, 0, byteRead);
        }
        inputStream.close();
        fileOutputStream.flush();
        fileOutputStream.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}


由于本人安卓知识及技术有限,代码如有错误或不足请评论指出,非常感谢!


猜你喜欢

转载自blog.csdn.net/u013642500/article/details/80069811
今日推荐