Java 如何在 Android 中将文件转换为 base 64(如 .pdf、.txt)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21601278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a file to base 64 (like .pdf,.txt) in Android?
提问by Basheer
How to covert the SD-card documents (.pdf,.txt) to base 64 string and string send to the server
如何将 SD 卡文件 (.pdf,.txt) 转换为 base 64 字符串并将字符串发送到服务器
采纳答案by Charles Stevens
Try these codes
试试这些代码
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
String encodeFileToBase64Binary = encodeFileToBase64Binary(yourFile);
private static String encodeFileToBase64Binary(File fileName) throws IOException {
byte[] bytes = loadFile(fileName);
byte[] encoded = Base64.encodeBase64(bytes);
String encodedString = new String(encoded);
return encodedString;
}
回答by pshegger
All you have to do is read the file to a byte array, and then use Base64.encodeToString(byte[], int)to convert it to a Base64 string.
您所要做的就是将文件读取到一个字节数组,然后使用Base64.encodeToString(byte[], int)将其转换为 Base64 字符串。
回答by Vrushi Patel
this method worked for me
这种方法对我有用
String encodeFileToBase64Binary = encodeFileToBase64Binary(yourFile);
private String encodeFileToBase64Binary(File yourFile) {
int size = (int) yourFile.length();
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(yourFile));
buf.read(bytes, 0, bytes.length);
buf.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String encoded = Base64.encodeToString(bytes,Base64.NO_WRAP);
return encoded;
}