我尝试使用下面的代码为文件生成一个 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,则 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) {}
}
关于java - 如何获取文件的 base64?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25519376/