如何获取文件的base64?

时间:2014-08-27 05:16:11

标签: 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();

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

2 个答案:

答案 0 :(得分:4)

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

这就是全部:

String base64 = DatatypeConverter.printBase64Binary(Files.readAllBytes(
    Paths.get("path/to/file")));

修改

如果您使用的是Java 6,则FilesPaths不可用(它们是在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) {}
}

答案 1 :(得分:0)

添加以下内容:

    String result = Base64.encode(output.toString().getBytes());