Skip to content

Commit b1859db

Browse files
authored
Merge pull request networknt#174 from networknt/feature/util_file_to_bytebuffer
feat(util): Add toByteBuffer overload util method to convert files.
2 parents 2d1f6fa + 73d81e1 commit b1859db

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

utility/pom.xml

+4
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,10 @@
5454
<groupId>org.owasp.encoder</groupId>
5555
<artifactId>encoder</artifactId>
5656
</dependency>
57+
<dependency>
58+
<groupId>commons-io</groupId>
59+
<artifactId>commons-io</artifactId>
60+
</dependency>
5761

5862
<dependency>
5963
<groupId>ch.qos.logback</groupId>

utility/src/main/java/com/networknt/utility/NioUtils.java

+17
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.networknt.utility;
22

3+
import org.apache.commons.io.IOUtils;
34
import org.slf4j.Logger;
45
import org.slf4j.LoggerFactory;
56

@@ -238,6 +239,22 @@ public static ByteBuffer toByteBuffer(String s) {
238239
return buffer;
239240
}
240241

242+
/**
243+
* Convert a File into a ByteBuffer
244+
* @param file File to be converted
245+
* @return ByteBuffer containing the file
246+
*/
247+
public static ByteBuffer toByteBuffer(File file) {
248+
ByteBuffer buffer = ByteBuffer.allocateDirect((int) file.length());
249+
try {
250+
buffer.put(IOUtils.toByteArray(new FileInputStream(file)));
251+
} catch (IOException e) {
252+
logger.error("Failed to write file to byte array: " + e.getMessage());
253+
}
254+
buffer.flip();
255+
return buffer;
256+
}
257+
241258
/**
242259
* get temp dir from OS.
243260
*

0 commit comments

Comments
 (0)