Skip to content

Commit cb160fd

Browse files
committed
FileUtils: add method to read contents of a file
1 parent 6bfb5be commit cb160fd

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/main/java/org/scijava/util/FileUtils.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434

3535
package org.scijava.util;
3636

37+
import java.io.DataInputStream;
3738
import java.io.File;
3839
import java.io.FileInputStream;
3940
import java.io.FilenameFilter;
@@ -132,6 +133,24 @@ public static Date getModifiedTime(final File file) {
132133
return c.getTime();
133134
}
134135

136+
/**
137+
* Reads the contents of the given file into a new byte array.
138+
*
139+
* @see DigestUtils#string(byte[]) To convert a byte array to a string.
140+
* @throws IOException If the file cannot be read.
141+
*/
142+
public static byte[] readFile(final File file) throws IOException {
143+
final long length = file.length();
144+
if (length > Integer.MAX_VALUE) {
145+
throw new IllegalArgumentException("File too large");
146+
}
147+
final DataInputStream dis = new DataInputStream(new FileInputStream(file));
148+
final byte[] bytes = new byte[(int) length];
149+
dis.readFully(bytes);
150+
dis.close();
151+
return bytes;
152+
}
153+
135154
/**
136155
* A regular expression to match filenames containing version information.
137156
* <p>

0 commit comments

Comments
 (0)