From 6afb7f8f1b7cff043988d3840fda19b9e77d8701 Mon Sep 17 00:00:00 2001 From: OLEGSHA Date: Mon, 31 Aug 2020 18:32:54 +0300 Subject: [PATCH] Added Resource.readAsBytes to read a resource to a ByteBuffer --- .../progressia/common/resource/Resource.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/main/java/ru/windcorp/progressia/common/resource/Resource.java b/src/main/java/ru/windcorp/progressia/common/resource/Resource.java index ce675dc..bd796c4 100644 --- a/src/main/java/ru/windcorp/progressia/common/resource/Resource.java +++ b/src/main/java/ru/windcorp/progressia/common/resource/Resource.java @@ -21,7 +21,11 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; +import java.nio.ByteBuffer; +import org.lwjgl.BufferUtils; + +import com.google.common.io.ByteStreams; import com.google.common.io.CharStreams; import ru.windcorp.progressia.Progressia; @@ -49,5 +53,26 @@ public class Resource extends Named { throw new RuntimeException(e); // TODO handle gracefully } } + + public ByteBuffer readAsBytes(ByteBuffer output) { + byte[] byteArray; + try (InputStream stream = getInputStream()) { + byteArray = ByteStreams.toByteArray(stream); + } catch (IOException e) { + throw new RuntimeException(e); // TODO handle gracefully + } + + if (output == null || output.remaining() < byteArray.length) { + output = BufferUtils.createByteBuffer(byteArray.length); + } + + output.put(byteArray); + + return output; + } + + public ByteBuffer readAsBytes() { + return readAsBytes(null); + } }