Skip to content

Instantly share code, notes, and snippets.

@anta40
Forked from amrishodiq/GetFileContents.java
Last active October 19, 2018 15:47
Show Gist options
  • Save anta40/d697adb2f539a539a017 to your computer and use it in GitHub Desktop.
Save anta40/d697adb2f539a539a017 to your computer and use it in GitHub Desktop.
/**
* Method to get all bytes from a file.
*
* @param path
* @return
* @throws IOException
*/
public static byte[] getFileContent(String path) throws IOException {
FileConnection file = null;
if (path.startsWith("file://"))
path = path.substring(7);
else if (!path.startsWith("/"))
path = "/" + path;
try {
file = (FileConnection) Connector.open("file://" + path,
Connector.READ);
int fileSize = (int) file.fileSize();
if (fileSize > 0) {
byte[] data = new byte[fileSize];
InputStream input = file.openInputStream();
input.read(data);
Thread.yield();
input.close();
return data;
} else {
throw new NullPointerException("File " + path + " is empty.");
}
} catch (IOException e) {
throw e;
} finally {
if (file != null && file.isOpen())
file.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment