Skip to content

Commit

Permalink
Fix resource leak bug (#5251)
Browse files Browse the repository at this point in the history
Signed-off-by: Alfusainey Jallow <[email protected]>
  • Loading branch information
Alfusainey authored Jul 5, 2023
1 parent 532e537 commit 368e1c7
Showing 1 changed file with 8 additions and 11 deletions.
19 changes: 8 additions & 11 deletions app/src/main/java/fr/free/nrw/commons/filepicker/PickedFiles.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,18 +56,13 @@ private static File tempImageDirectory(@NonNull Context context) {
* @param in input stream of source file.
* @param file destination file
*/
private static void writeToFile(InputStream in, File file) {
try {
OutputStream out = new FileOutputStream(file);
private static void writeToFile(InputStream in, File file) throws IOException {
try (OutputStream out = new FileOutputStream(file)) {
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Expand All @@ -79,8 +74,9 @@ private static void writeToFile(InputStream in, File file) {
* @throws IOException (File input stream exception)
*/
private static void copyFile(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
writeToFile(in, dst);
try (InputStream in = new FileInputStream(src)) {
writeToFile(in, dst);
}
}

/**
Expand Down Expand Up @@ -157,11 +153,12 @@ static void scanCopiedImages(Context context, List<File> copiedImages) {
* @return Uploadable file ready for tag redaction.
*/
public static UploadableFile pickedExistingPicture(@NonNull Context context, Uri photoUri) throws IOException, SecurityException {// SecurityException for those file providers who share URI but forget to grant necessary permissions
InputStream pictureInputStream = context.getContentResolver().openInputStream(photoUri);
File directory = tempImageDirectory(context);
File photoFile = new File(directory, UUID.randomUUID().toString() + "." + getMimeType(context, photoUri));
if (photoFile.createNewFile()) {
writeToFile(pictureInputStream, photoFile);
try (InputStream pictureInputStream = context.getContentResolver().openInputStream(photoUri)) {
writeToFile(pictureInputStream, photoFile);
}
} else {
throw new IOException("could not create photoFile to write upon");
}
Expand Down

0 comments on commit 368e1c7

Please sign in to comment.