Java 将文件编码为 Base64 字符串 与其他编码字符串匹配

2022-09-03 03:16:27
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;
}

获取编码字符串

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

编码字符串为:

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

使用其他源从文件编码字符串。

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

当我试图匹配两个编码字符串时,我得到了一个不匹配。请建议将文件编码到base64的方法,以匹配从其他来源找到的编码字符串。我试过和.StandardCharsets.UTF_8StandardCharsets.US_ASCII


答案 1

您已经在使用apache commons-codec,因此我建议添加commons-io来读取文件。这样,您就可以删除 loadFile() 方法,只需:

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

答案 2

这是一个没有任何必需依赖项的解决方案(Apacha等人),只需要JDK 8 +:

import java.util.Base64;
import java.nio.file.Files;

private static String encodeFileToBase64(File file) {
    try {
        byte[] fileContent = Files.readAllBytes(file.toPath());
        return Base64.getEncoder().encodeToString(fileContent);
    } catch (IOException e) {
        throw new IllegalStateException("could not read file " + file, e);
    }
}