1

I have a zip file created by my Android application on the tablet I am also using for tests later. I can open it on the Android tablet and also on my PC, i.e. it is not corrupted. I added this .zip file to /res/raw folder of my Android test project. Now I would like to copy this file for one of my junit testcases to Android device. For that, I use the following code:

    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;

The zip file with the correct file is created, but when opened, it gives an error message: bad zip file. What should I change for being able to open the zip file after the transfer?

Rebane Lumes
  • 393
  • 2
  • 4
  • 18

1 Answers1

0

I did not find out, what my code was doing wrong, but I found a workaround that serves the same purpose:

The result:

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);
    }
}
Community
  • 1
  • 1
Rebane Lumes
  • 393
  • 2
  • 4
  • 18