Why doesn't Base64 Encoding of a byte[] in Java work?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | import java.io.*; import java.nio.*; import java.util.Base64; import java.util.UUID; import java.io.UnsupportedEncodingException; public class Abc { public static String readFileAsString(String filePath) throws IOException { DataInputStream dis = new DataInputStream(new FileInputStream(filePath)); try { long len = new java.io.File(filePath).length(); if (len > Integer.MAX_VALUE) throw new IOException("File" + filePath +" too large") byte[] bytes = new byte[(int) len]; dis.readFully(bytes); String ans = new String(bytes,"UTF-8"); return ans; } finally { dis.close(); } } public static void main(String args[]) throws IOException { String base64encodedString = null; FileOutputStream stream = new FileOutputStream("C:\\\\Users\\\\EMP142738\\\\Desktop\\\ ew folder\\\ eadhjbdsdsefd.pdf"); String filePath = new String("C:\\\\Users\\\\EMP142738\\\\Desktop\\\ ew folder\\\ eaders Quick Ref Card.pdf"); try { base64encodedString = java.util.Base64.getUrlEncoder().encodeToString(new Abc().readFileAsString(filePath).getBytes("utf-8")); } catch (IOException e) { e.printStackTrace(); } try { byte[] base64decodedBytes = java.util.Base64.getUrlDecoder().decode(base64encodedString); stream.write(base64decodedBytes); } catch(IOException e){ e.printStackTrace();} finally { stream.close(); }//catch (FileNotFoundException e) { // e.printStackTrace(); } } |
我正在尝试使用Base64编码和解码PDF文件。我正在做的是将PDF(二进制文件)转换为ByteArray,然后将ByteArray作为字符串返回。然后,我使用java.util.Base64在Base64中对该字符串进行编码。当我尝试回溯整个过程时,我可以转换PDF(二进制文件),但文件已损坏/损坏。同样,整个过程(编码解码)后的输出文件明显大于输入文件。我希望它们的大小相同。我在这里做错了什么?
编辑1(7/13/16):
在主要方法中,我按照吉姆的建议修改了代码。
阅读相同的文档后,我尝试使用Base64.encode(byte [] src)。但是,它始终显示错误"找不到符号Base64.encode(byte [])"。但是我使用了来自同一Class(java.util.Base64.Encoder)的encodetoString方法。我在这里无法理解问题。
这是从readFileAsString方法返回byte []后使用的修改后的main方法。
1 2 3 4 5 6 7 8 9 | public void main(String args[]) throws IOException { String filePath = new String("C:\\\\Users\\\\EMP142738\\\\Desktop\\\ ew folder\\\ eaders Quick Ref Card.pdf"); byte[] src = new Abc().readFileAsString(filePath); byte[] destination = Base64.encode(src); } |
问题出在您的流程中
1 |
您需要省略到
1 | byte[] -> base64 string |
转换为String会破坏二进制流,因为它涉及从输入字符集到16位Unicode字符的解码操作。