Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Android Data Persistence File Storage Writing to Internal Storage

Alwin Lazar V
Alwin Lazar V
5,267 Points

how to modify this code I have stuck this challenge

please help to pass this section and anyone please tell more about this?

FileUtilities.java
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileUtilities {

  public static boolean copyResult;

  public static void saveAssetImage(Context context, String assetName) {
    File fileToWrite = new File(context.getFilesDir(), assetName);
    AssetManager assetManager = context.getAssets();

    try {
      InputStream in = assetManager.open(assetName);
      FileOutputStream out = new FileOutputStream(fileToWrite);
      copyResult = copyFile(in, out);
    } catch(FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  private static boolean copyFile(InputStream in, FileOutputStream out) {
    // Copy magic intentionally omitted
     byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);

 if (fileToWrite.exists() == false) { copyResult = copyFile(in, out); }

    return true;
        }
  }
}

1 Answer

Mohammed Amin
Mohammed Amin
5,445 Points

It's asking you to execute the logic that copies the file only if the file does not already exist. The place where the logic gets executed is in the try-catch block. So you have to wrap the try catch block in an if that checks if the file does not exist. Nothing else in the file should be modified.

Something like:

if (!fileToWrite.exists()} {
    // try-catch block
}