1

我有一个由我的 Android 应用程序在平板电脑上创建的 zip 文件,我稍后也用于测试。我可以在 Android 平板电脑和我的 PC 上打开它,即它没有损坏。我将此 .zip 文件添加到我的 Android 测试项目的 /res/raw 文件夹中。现在我想将我的一个 junit 测试用例的这个文件复制到 Android 设备。为此,我使用以下代码:

    boolean success = false;
    File appDirectory = MainActivity.getContext().getExternalFilesDir(null);
    File pictureSketch = new File(appDirectory, sketchName+".zip");
    if (!appDirectory.exists()) {
        assertTrue("App directory could not be created.",appDirectory.mkdirs());    
    }

    InputStream in = activity.getResources().openRawResource(raw.pictest);
    FileOutputStream out = new FileOutputStream(pictureSketch);
    byte[] buff = new byte[1024];
    int read = 0;

    try {
       while ((read = in.read(buff)) > 0) {
          out.write(buff, 0, read);
       }
    } finally {
         in.close();

         out.close();
         success = true;
    }       

    return success;

已创建具有正确文件的 zip 文件,但打开时会显示错误消息:损坏的 zip 文件。我应该改变什么才能在传输后打开 zip 文件?

4

1 回答 1

0

我没有发现我的代码做错了什么,但我找到了一个可以达到相同目的的解决方法:

结果:

private void copyPicSketch() {  
    AssetManager assetManager = getInstrumentation().getContext().getResources().getAssets();
    String[] files = null;
    try {
        files = assetManager.list("");
    } catch (IOException e) {
        Log.e("tag", "Failed to get asset file list.", e);
    }
    for(String filename : files) {
        if (filename.contains(sketchName)) {
            InputStream in = null;
            OutputStream out = null;
            try {
              in = assetManager.open(filename);
              File outFile = new File(activity.getExternalFilesDir(null), filename);
              out = new FileOutputStream(outFile);
              copyFile(in, out);
              in.close();
              in = null;
              out.flush();
              out.close();
              out = null;
            } catch(IOException e) {
                Log.e("tag", "Failed to copy asset file: " + filename, e);
            }               
        }
    }
}
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);
    }
}
于 2013-09-10T15:22:14.257 回答