【问题标题】:java android copy files assetsjava android复制文件资产
【发布时间】:2011-11-27 21:33:00
【问题描述】:

我有异步任务,必须将文件夹“文件”从资产写入 SD 卡上的文件夹。但没有任何效果。

final String sdDir = "/sdcard/izuchaika/";

new Thread(new Runnable() {
        public void run() {
            try {

                InputStream in = getAssets().open("Files");
                OutputStream out = new FileOutputStream(new File(sdDir));
                try {
                    byte[] bucket = new byte[32 * 1024];
                    int bytesRead = 0;
                    while (bytesRead != -1) {
                        bytesRead = in.read(bucket);
                        out.write(bucket, 0, bytesRead);
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                } finally {
                    try {
                        if (in != null)
                            in.close();
                        if (out != null)
                            out.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }

                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        }
    }).start();

Screen of folder tree

【问题讨论】:

  • 一般提示:永远不要硬编码外部存储/sd卡的路径(就像你在代码的第1行中所做的那样)。请改用Environment.getExternalStorageDirectory(),因为实际路径和存储类型因设备而异(例如,有些设备具有内置闪存而不是 SD 卡)

标签: java android file copy assets


【解决方案1】:

您正在将目录作为文件写入和读取。

替换

InputStream in = getAssets().open("Files");
OutputStream out = new FileOutputStream(new File(sdDir));

InputStream in = getAssets().open("Files/exit.png");
OutputStream out = new FileOutputStream(new File(sdDir+"/exit.png"));

【讨论】:

  • 还有,记得在清单中请求写入 SD 卡的权限
  • InputStream in = getAssets().open("Files/exit.png");但是这样我就可以只读文件了?我需要阅读所有文件夹,因为有很多文件。
  • 然后列出assets目录下的文件,做一个循环。有什么问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-11
  • 1970-01-01
  • 1970-01-01
  • 2014-01-30
  • 1970-01-01
  • 2016-03-23
  • 2012-01-14
相关资源
最近更新 更多