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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37066216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 18:58:34  来源:igfitidea点击:

Java Encode file to Base64 string To match with other encoded string

javastringencodingutf-8base64

提问by Sanket Sawant

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_8and StandardCharsets.US_ASCII.

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

回答by gfelisberto

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:

您已经在使用 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);
}

回答by the hand of NOD

Since Java 8 you can use the class java.util.Base64and the corresponding inner classes:

从 Java 8 开始,您可以使用该类java.util.Base64和相应的内部类:

  • java.util.Base64.Encoder
  • java.util.Base64.Decoder
  • java.util.Base64.Encoder
  • java.util.Base64.Decoder

See JavaDoc: Base64-Doc

请参阅 JavaDoc:Base64-Doc

And a sample for the use: Example from Oracle

以及一个使用示例来自 Oracle 的示例

回答by Big D.

This example worked great for me: https://grokonez.com/java/java-advanced/java-8-encode-decode-an-image-base64

这个例子对我很有用:https: //grokonez.com/java/java-advanced/java-8-encode-decode-an-image-base64

public static String encoder(String filePath) {
        String base64File = "";
        File file = new File(filePath);
        try (FileInputStream imageInFile = new FileInputStream(file)) {
            // Reading a file from file system
            byte fileData[] = new byte[(int) file.length()];
            imageInFile.read(fileData);
            base64File = Base64.getEncoder().encodeToString(fileData);
        } catch (FileNotFoundException e) {
            System.out.println("File not found" + e);
        } catch (IOException ioe) {
            System.out.println("Exception while reading the file " + ioe);
        }
        return base64File;
    }

回答by Patrick Favre

Here is a solution without any required dependencies (Apacha et al.) requiring only JDK 8+:

这是一个不需要任何依赖项(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);
    }
}