pdf转base64
//转base64 public String fileToBase64() { // String imgFilePath = "C:\\Users\\zlf\\Desktop\\pdf\\042002200211_87910810.pdf"; String imgFilePath = "C:\\Users\\zlf\\Desktop\\pdf\\【高德打车-38.65元-1个行程】高德打车电子行程单.pdf"; String[] res = imgFilePath.split("\\."); String pos = res[res.length - 1]; byte[] data = null; // 读取图片字节数组 try { InputStream in = new FileInputStream(imgFilePath); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } String data1 = Base64.encodeBase64String(data); System.out.println(data1); return data1; }
Base64转pdf
//转pdf @Test public void sfad(){ String s = this.fileToBase64(); byte[] decode = Base64.decodeBase64(s); File file = new File("d:/file2.pdf");//pdf保存路径 try { FileOutputStream fop = new FileOutputStream(file); try { fop.write(decode); fop.flush(); fop.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } }
这里的Base64我用的commons-codec:1.15
可以用jdk1.8的base64,如下
public static void main(String[] args) throws UnsupportedEncodingException { String string = "12345"; System.out.println("old string: " + string); String base64 = Base64.getEncoder().encodeToString(string.getBytes("UTF-8")); System.out.println("base64 decode: " + base64); byte[] bytes = Base64.getDecoder().decode(base64); System.out.println("base64 encode: " + new String(bytes, "UTF-8")); }
标签:Base64,String,base64,new,字符串,pdf,out From: https://www.cnblogs.com/ketoli/p/17995791