Java encodes the file as a Base64 string to match other encoded strings
•
Java
private static String encodeFileToBase64Binary(String fileName)
private static String encodeFileToBase64Binary(String fileName) throws IOException { File file = new File(fileName); byte[] bytes = loadFile(file); byte[] encoded = Base64.encodeBase64(bytes); String encodedString = new String(encoded,StandardCharsets.US_ASCII); return encodedString; } private static byte[] loadFile(File file) throws IOException { InputStream is = new FileInputStream(file); long length = file.length(); if (length > Integer.MAX_VALUE) { // File is too large } byte[] bytes = new byte[(int)length]; int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead=is.read(bytes,offset,bytes.length-offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { throw new IOException("Could not completely read file "+file.getName()); } is.close(); return bytes; }
//Get encoding string
String encoded=encodeFileToBase64Binary("file.fmr");
//The encoded string is:
Rk1SACAyMAAAAAFiAAABQAHgAMUAxQEAAABGNkDZADP/SEC8AD6CSECqAEcGSED+AFJtO0CgAGCKZEC6AGuFZEDgAHz1ZECzAI6HZEENAJluNEBWAJ4ZZEB1AKkTZEECALbuZEA/ALqfSECCALySSECxAMP/ZECIAMURVUAXAN2jGkCnAOD8ZEAoAOWlZEBnAOyhLkCyAP/tZECHAQMSGkD8AQTdZECfASKFGkCHASUaGkA1ASy6ZEDAAS3JZEDPAS7NZEAnATG4ZEDxATzOZEBOAUPLZEBzAVbuGkCAAWF8NEDTAWsxLkDnAXa0LkC/AX2nLkC0AYojIEBMAYvkSEDJAa0fT0CsAbwVIIDqANTsZIDIAPfnZICbAQKHO4D5AR/XZIBlASS7IIEoASbYO4CsAUetLoDvAVXSZIDaAVvDO4EHAWrLZICsAX2fNIDnAYEwNIDQAZKnT4BfAZxtZAAA
//A string encoded from a file using another source
Rk1SACAyMAAAAAFiAAABQAHgAMUAxQEAAABGNkCLACELSEDAADYDZEEYAGFxO0DGAGJ9SEC1AGkCSEA6AHWYVUDJAHp5ZEBEAHwVZECVAJgIZEEaALHrZEB4ALuOZEELAMFqZEEzAM/sNEDRANvwZEBkAN0VZECcAOIAZEEwAOjnLkEvAPXlO0CnAP71ZEB7AQYRNEBdAQ0eZED8ARDhZEDXASXcZECZAS3uGkBoAT4eO0AUAUMxSEA7AUYqZEDxAUnSZECmAVNDO0EIAXDHSEDYAXW7ZEEUAXXKSEEGAYY8IEEhAYrDNEDfAZ81ZEDQAcGqLoEBAC/7O4EGAE7zVYB+AP2QSICEARuLZIBnATUfO4D/ATXaZIDEATjSZIDRATrVZICnATvSNIBTATwnZIARAV1LGoB1AV2oO4CrAV68SIDnAWHGZIB+AWauNICVAX0ySICNAYytO4CJAZorSAAA
When I tried to match the encoded string, I got a mismatch Please suggest encoding files to Base64 to match encoding strings found from other sources I tried standard charsets UTF_ 8 and standardcharsets US_ ASCII.
Solution
You have used Apache commons codec, so I suggest adding commons IO to read the file In this way, you can delete your LoadFile () method, just:
private static String encodeFileToBase64Binary(String fileName) throws IOException { File file = new File(fileName); byte[] encoded = Base64.encodeBase64(FileUtils.readFileToByteArray(file)); return new String(encoded,StandardCharsets.US_ASCII); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码