[英]How can I get base64 for a file?
我嘗試使用下面的代碼為文件生成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) {}
}
添加以下內容:
String result = Base64.encode(output.toString().getBytes());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.