Android File To Base64 using streaming sometimes missed 2 bytes

前端 未结 2 713
暖寄归人
暖寄归人 2020-12-20 19:32

i am writing to ask for the proper solution for solving the following difficulties:

I am required to encode the file in Base64 format, and there is no way for me to

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-20 20:17

    Your streams should be flushed before using them for other operations and before closing them:

    FileOutputStream fout = new FileOutputStream(path + ".txt");
    //this is for printing out the base64 content
    FileInputStream fin = new FileInputStream(path);
    System.out.println("File Size:" + path.length());   // path.getTotalSpace() is the filesystem size
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    Base64OutputStream base64out = new Base64OutputStream(os,Base64.NO_WRAP);
    
    byte[] buffer = new byte[3 * 512];
    int len = 0;
    while ((len = fin.read(buffer)) >= 0) {
        base64out.write(buffer, 0, len);
    }
    System.out.println("Encoded Size:" + os.size());
    
    base64out.write(System.lineSeparator().getBytes());   
    base64out.flush();  // to be sure that everything is in the byte array
    String result = new String(os.toByteArray(), "UTF-8");
    fout.write(os.toByteArray());
    fout.flush();  // make sure everything is written
    fout.close();
    base64out.close();
    os.close();
    fin.close();
    
    System.out.println("new File Size:" + new File(path + ".txt").length()); // prints out the size of the finished file
    
    return result;
    

提交回复
热议问题