编程语言
首页 > 编程语言> > java-如何获取文件的base64?

java-如何获取文件的base64?

作者:互联网

我尝试使用下面的代码为文件生成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文件名.请告诉我

解决方法:

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

这就是所有步骤:

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

编辑:

如果您使用的是Java 6,则无法使用“文件和路径”(它们是在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) {}
}

标签:base64,file-io,email,mime-types,java
来源: https://codeday.me/bug/20191029/1958241.html