如何获取文件的base64?

Kot*_*ati 4 java email file-io base64 mime-types

我尝试使用以下代码为文件生成 base64 并作为字符串返回。如果文件大小很小,我能够得到。

StringBuffer output = new StringBuffer();

        Process p;
        try {
            p = Runtime.getRuntime().exec(command);
            p.waitFor();
            BufferedReader reader = 
                            new BufferedReader(new InputStreamReader(p.getInputStream()));

                        String line = "";           
            while ((line = reader.readLine())!= null) {
                output.append(line + "\n");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return output.toString();
Run Code Online (Sandbox Code Playgroud)

如果有任何其他方法可以获取文件的base64。我传递的命令是base64 文件名。请让我知道

icz*_*cza 5

您不需要为此使用外部程序,Java 具有内置的 Base64 编码/解码功能。

这就是全部:

String base64 = DatatypeConverter.printBase64Binary(Files.readAllBytes(
    Paths.get("path/to/file")));
Run Code Online (Sandbox Code Playgroud)

编辑:

如果您使用的是 Java 6,Files并且Paths不可用(它们是在 Java 7.0 中添加的)。这是一个 Java 6 兼容的解决方案:

File f = new File("path/to/file");
byte[] content = new byte[(int) f.length()];
InputStream in = null;
try {
    in = new FileInputStream(f);
    for (int off = 0, read;
        (read = in.read(content, off, content.length - off)) > 0;
        off += read);

    String base64 = DatatypeConverter.printBase64Binary(content);
} catch (IOException e) {
    // Some error occured
} finally {
    if (in != null)
        try { in.close(); } catch (IOException e) {}
}
Run Code Online (Sandbox Code Playgroud)