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 trialMalcolm Mutambanengwe
4,205 Pointsdatabase write only
Can't see my error Ben Jakuben
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
Steve Hunter
57,712 PointsHi 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.
Malcolm Mutambanengwe
4,205 PointsHi Steve Hunter just saw your reply. Let me try that out.
Steve Hunter
57,712 PointsShould work fine - I did test it out!
Malcolm Mutambanengwe
4,205 PointsHi Evans Attafuah
Tried but it didn't work. Thanks for your help though.
Malcolm Mutambanengwe
4,205 PointsMalcolm Mutambanengwe
4,205 Pointsthe grandmaster Steve is here
Like so . . .
Steve Hunter
57,712 PointsSteve Hunter
57,712 PointsLooks correct, yes. Leave the try/catch block where it is but wrap the
if
statement around it. Should work fine.