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

database write only

Can't see my error Ben Jakuben

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){
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);// Copy magic intentionally omitted
  }
}

3 Answers

Hi Mal,

I answered in your other post.

Ignore the copyFile method; as the comment says, the code there is intentionally omitted.

You want to prevent the copyFile method being called unless the file doesn't already exist. The call is made within the try/catch block.

Before entering that block, do the test to see if the file doesn't exist; use the .exists() method and surround the try/catch with an if statement:

if (!fileToWrite.exists()) {
  // existing try/catch code here
}

Steve.

the grandmaster Steve is here

Like so . . .

if (!fileToWrite.exists()) {
    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();
    }
  }
 }

Looks correct, yes. Leave the try/catch block where it is but wrap the if statement around it. Should work fine.

Hi Steve Hunter just saw your reply. Let me try that out.

Should work fine - I did test it out! :+1: :smile:

Hi Evans Attafuah

Tried but it didn't work. Thanks for your help though.