如何在android中将文件转换为base64Binary?

如何在android中将文件转换为base64Binary?,android,Android,下面的代码用于将文件转换为bytearray public static byte[] convertFileToByteArray(File f) { byte[] byteArray = null; try { @SuppressWarnings("resource") InputStream inputStream = new FileInputStream(f); ByteArrayOutputStream bos = n

下面的代码用于将文件转换为bytearray

 public static byte[] convertFileToByteArray(File f) {
    byte[] byteArray = null;
    try {
        @SuppressWarnings("resource")
        InputStream inputStream = new FileInputStream(f);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024 * 8];
        int bytesRead = 0;

        while ((bytesRead = inputStream.read(b)) != -1) {
            bos.write(b, 0, bytesRead);
        }

        byteArray = bos.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return byteArray;
}
但是我需要一个将文件转换为二进制格式的代码。

试试这个:

获取字节数组文件:

File file= new File("path file");
byte[] fileByte=convertFileToByteArray(file);
然后转换为字节数组中的base64:

byte[] file_in_base64 = Base64.encode(fileByte, Base64.DEFAULT);
将字节数组转换为二进制:

String toBinary( byte[] bytes )
{
    StringBuilder sb = new StringBuilder(bytes.length * Byte.SIZE);
    for( int i = 0; i < Byte.SIZE * bytes.length; i++ )
        sb.append((bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1');
    return sb.toString();
}
字符串到二进制(字节[]字节)
{
StringBuilder sb=新的StringBuilder(bytes.length*Byte.SIZE);
对于(int i=0;isb.append((字节[i/Byte.SIZE]看,如果你想要的话,我在那里更改了我的答案。
将字节数组转换为二进制:
。不。这将字节数组转换为字符串。
我用base64完成了,但我想转换base64二进制格式。
对不起,我不理解你想要的。
base64
中的文件已经是一个字节数组,并且尽可能是二进制的。@Ludger Thanks的代码..在asynctask中使用JsonStringer将二进制数据发布到服务器时出现内存不足异常。请建议我使用其中提到的二进制文件将字节转换为0和1,但因为java字节数组中的字符串可以是:byte[]exampleByte=new byte[]{0x42,0x69,0x10,0x0d};字节数组已经是二进制的。您到底想要什么?