diff --git a/modules/java/generator/android/java/org/opencv/android/Utils.java b/modules/java/generator/android/java/org/opencv/android/Utils.java index eef4c45622..80e85f5f88 100644 --- a/modules/java/generator/android/java/org/opencv/android/Utils.java +++ b/modules/java/generator/android/java/org/opencv/android/Utils.java @@ -23,24 +23,20 @@ public class Utils { public static String exportResource(Context context, int resourceId, String dirname) { String fullname = context.getResources().getString(resourceId); String resName = fullname.substring(fullname.lastIndexOf("/") + 1); - try { - InputStream is = context.getResources().openRawResource(resourceId); + try (InputStream is = context.getResources().openRawResource(resourceId)) { File resDir = context.getDir(dirname, Context.MODE_PRIVATE); File resFile = new File(resDir, resName); - FileOutputStream os = new FileOutputStream(resFile); - - byte[] buffer = new byte[4096]; - int bytesRead; - while ((bytesRead = is.read(buffer)) != -1) { - os.write(buffer, 0, bytesRead); + try (FileOutputStream os = new FileOutputStream(resFile)) { + byte[] buffer = new byte[4096]; + int bytesRead; + while ((bytesRead = is.read(buffer)) != -1) { + os.write(buffer, 0, bytesRead); + } } - is.close(); - os.close(); return resFile.getAbsolutePath(); } catch (IOException e) { - e.printStackTrace(); throw new CvException("Failed to export resource " + resName + ". Exception thrown: " + e); } @@ -53,19 +49,22 @@ public class Utils { public static Mat loadResource(Context context, int resourceId, int flags) throws IOException { - InputStream is = context.getResources().openRawResource(resourceId); - ByteArrayOutputStream os = new ByteArrayOutputStream(is.available()); + byte[] data; + int dataLength; - byte[] buffer = new byte[4096]; - int bytesRead; - while ((bytesRead = is.read(buffer)) != -1) { - os.write(buffer, 0, bytesRead); + try (InputStream is = context.getResources().openRawResource(resourceId); + ByteArrayOutputStream os = new ByteArrayOutputStream(is.available())) { + byte[] buffer = new byte[4096]; + int bytesRead; + while ((bytesRead = is.read(buffer)) != -1) { + os.write(buffer, 0, bytesRead); + } + data = os.toByteArray(); + dataLength = os.size(); } - is.close(); - Mat encoded = new Mat(1, os.size(), CvType.CV_8U); - encoded.put(0, 0, os.toByteArray()); - os.close(); + Mat encoded = new Mat(1, dataLength, CvType.CV_8U); + encoded.put(0, 0, data); Mat decoded = Imgcodecs.imdecode(encoded, flags); encoded.release();