如何将base64转换为不同类型的文件(doc,pdf,word ..etc)?

时间:2018-11-14 08:21:22

标签: java android base64

我正在研究项目,我必须下载从服务器收到的附件。我必须利用base64数据并将其转换为适当的类型并下载。它对图像非常适合我(基本64 =>字节=>位图),但是我发现其他类型(txt,pdf ..etc)的麻烦

1 个答案:

答案 0 :(得分:0)

尝试

 try {

            File sdcard = Environment.getExternalStorageDirectory();
            File file = new File(sdcard,"test.pdf");

            File new_file_name = new File(sdcard,"new_file.pdf");

            byte[] input_file = IOUtil.readFile(file);


            byte[] encodedBytes = Base64.encode(input_file,URL_SAFE);
            String encodedString = new String(encodedBytes);
            byte[] decodedBytes = Base64.decode(encodedString.getBytes(),URL_SAFE);

            FileOutputStream fos = new FileOutputStream(new_file_name);
            fos.write(decodedBytes);
            fos.flush();
            fos.close();
        }catch (Exception e)
        {
            Log.e("ERROR",e.toString());
        }

还有IOUtil类

public class IOUtil {

    public static byte[] readFile(String file) throws IOException {
        return readFile(new File(file));
    }

    public static byte[] readFile(File file) throws IOException {
        // Open file
        RandomAccessFile f = new RandomAccessFile(file, "r");
        try {
            // Get and check length
            long longlength = f.length();
            int length = (int) longlength;
            if (length != longlength)
                throw new IOException("File size >= 2 GB");
            // Read file and return data
            byte[] data = new byte[length];
            f.readFully(data);
            return data;
        } finally {
            f.close();
        }
    }
}

此代码包含编码和解码部分