public static String getFileBinary(String fileName) { BufferedInputStream bin = null; ByteArrayOutputStream baos = null; BufferedOutputStream bout = null; try { bin = new BufferedInputStream(new FileInputStream(new File(fileName))); baos = new ByteArrayOutputStream(); bout = new BufferedOutputStream(baos); byte[] buffer = new byte[1024]; int len = bin.read(buffer); while (len != -1) { bout.write(buffer, 0, len); len = bin.read(buffer); } bout.flush(); byte[] bytes = baos.toByteArray(); return Base64.getEncoder().encodeToString(bytes); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { bin.close(); bout.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }
public static void base64StringToFile(String base64sString, String fileName) { BufferedInputStream bin = null; FileOutputStream fout = null; BufferedOutputStream bout = null; try { byte[] bytes =Base64.getDecoder().decode(base64sString); bin = new BufferedInputStream(new ByteArrayInputStream(bytes)); File file = new File(fileName); fout = new FileOutputStream(file); bout = new BufferedOutputStream(fout); byte[] buffers = new byte[1024]; int len = bin.read(buffers); while (len != -1) { bout.write(buffers, 0, len); len = bin.read(buffers); } bout.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { bin.close(); fout.close(); bout.close(); } catch (IOException e) { e.printStackTrace(); } } }