java base64 编码文件,Java编码文件为Base64字符串与其他编码的字符串匹配

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;

}

// to get encode string

String encoded=encodeFileToBase64Binary("file.fmr");

// encoded string is :

Rk1SACAyMAAAAAFiAAABQAHgAMUAxQEAAABGNkDZADP/SEC8AD6CSECqAEcGSED+AFJtO0CgAGCKZEC6AGuFZEDgAHz1ZECzAI6HZEENAJluNEBWAJ4ZZEB1AKkTZEECALbuZEA/ALqfSECCALySSECxAMP/ZECIAMURVUAXAN2jGkCnAOD8ZEAoAOWlZEBnAOyhLkCyAP/tZECHAQMSGkD8AQTdZECfASKFGkCHASUaGkA1ASy6ZEDAAS3JZEDPAS7NZEAnATG4ZEDxATzOZEBOAUPLZEBzAVbuGkCAAWF8NEDTAWsxLkDnAXa0LkC/AX2nLkC0AYojIEBMAYvkSEDJAa0fT0CsAbwVIIDqANTsZIDIAPfnZICbAQKHO4D5AR/XZIBlASS7IIEoASbYO4CsAUetLoDvAVXSZIDaAVvDO4EHAWrLZICsAX2fNIDnAYEwNIDQAZKnT4BfAZxtZAAA

//encoded string from file using some other source.

Rk1SACAyMAAAAAFiAAABQAHgAMUAxQEAAABGNkCLACELSEDAADYDZEEYAGFxO0DGAGJ9SEC1AGkCSEA6AHWYVUDJAHp5ZEBEAHwVZECVAJgIZEEaALHrZEB4ALuOZEELAMFqZEEzAM/sNEDRANvwZEBkAN0VZECcAOIAZEEwAOjnLkEvAPXlO0CnAP71ZEB7AQYRNEBdAQ0eZED8ARDhZEDXASXcZECZAS3uGkBoAT4eO0AUAUMxSEA7AUYqZEDxAUnSZECmAVNDO0EIAXDHSEDYAXW7ZEEUAXXKSEEGAYY8IEEhAYrDNEDfAZ81ZEDQAcGqLoEBAC/7O4EGAE7zVYB+AP2QSICEARuLZIBnATUfO4D/ATXaZIDEATjSZIDRATrVZICnATvSNIBTATwnZIARAV1LGoB1AV2oO4CrAV68SIDnAWHGZIB+AWauNICVAX0ySICNAYytO4CJAZorSAAA

When i am trying to match both the encoded string , i am getting a missmatch.

please suggest method for encode file to base64 to match encoded string found from other source.

i have tried with StandardCharsets.UTF_8 and StandardCharsets.US_ASCII.

解决方案

You already using apache commons-codec so I recommend adding commons-io for reading the file. That way you can remove your loadFile() method and just have:

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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值