Skip to content

Instantly share code, notes, and snippets.

@thekalinga
Created August 28, 2019 13:04
Show Gist options
  • Save thekalinga/dcb7c62ca09b49fb0d9e759d96009b6c to your computer and use it in GitHub Desktop.
Save thekalinga/dcb7c62ca09b49fb0d9e759d96009b6c to your computer and use it in GitHub Desktop.
Base64 encode file content (eager fetch) in java8
public static String base64Encode(Path filePath) {
String base64EncodeFileConetnt = "";
try (InputStream fileStream = newInputStream(filePath)) {
// Reading a Image file from file system
byte[] fileData = new byte[(int) Files.size(filePath)];
//noinspection ResultOfMethodCallIgnored
fileStream.read(fileData);
base64EncodeFileConetnt = Base64.getEncoder().encodeToString(fileData);
} catch (FileNotFoundException e) {
System.out.println("File not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while reading the file " + ioe);
}
return base64EncodeFileConetnt;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment