簡體   English   中英

為什么Java中的byte []的Base64編碼不起作用?

[英]Why doesn't Base64 Encoding of a byte[] in Java work?

import java.io.*;
import java.nio.*;
import java.util.Base64;
import java.util.UUID;
import java.io.UnsupportedEncodingException;

public class Abc {

public static String readFileAsString(String filePath) throws IOException {
    DataInputStream dis = new DataInputStream(new FileInputStream(filePath));
    try {
        long len = new java.io.File(filePath).length();
        if (len > Integer.MAX_VALUE) throw new IOException("File " + filePath + " too large")
        byte[] bytes = new byte[(int) len];
        dis.readFully(bytes);
        String ans = new String(bytes, "UTF-8");
        return ans;


    } finally {
        dis.close();
    }
}

public static void main(String args[]) throws IOException {

    String base64encodedString = null;
    FileOutputStream stream = new FileOutputStream("C:\\Users\\EMP142738\\Desktop\\New folder\\Readhjbdsdsefd.pdf");


    String filePath = new String("C:\\Users\\EMP142738\\Desktop\\New folder\\Readers Quick Ref Card.pdf");
    try {

        base64encodedString = java.util.Base64.getUrlEncoder().encodeToString(new Abc().readFileAsString(filePath).getBytes("utf-8"));



    } catch (IOException e) {
        e.printStackTrace();
    }

    try {

        byte[] base64decodedBytes = java.util.Base64.getUrlDecoder().decode(base64encodedString);
        stream.write(base64decodedBytes);

    }   catch(IOException e){
    e.printStackTrace();}       
    finally {
stream.close();
}//catch (FileNotFoundException e) {
   //         e.printStackTrace();
        }
    }

我正在嘗試使用Base64編碼和解碼PDF文件。 我正在做的是將PDF(二進制文件)轉換為ByteArray,然后將ByteArray作為字符串返回。 然后,我使用java.util.Base64在Base64中對該字符串進行編碼。 當我嘗試回溯整個過程時,我可以轉換PDF(二進制文件),但文件已損壞/損壞。 同樣,整個過程(編碼解碼)后的輸出文件明顯大於輸入文件。 我希望它們的大小相同。 我在這里做錯了什么?

編輯1(7/13/16):在主要方法中,我根據吉姆的建議修改了代碼。 閱讀相同的文檔后,我嘗試使用Base64.encode(byte [] src)。 但是,它始終顯示錯誤“找不到符號Base64.encode(byte [])”。 但是我使用了來自同一Class(java.util.Base64.Encoder)的encodetoString方法。 我無法在這里了解問題。 這是從readFileAsString方法返回byte []后使用的修改后的main方法。

 public void main(String args[]) throws IOException {

    String filePath = new String("C:\\Users\\EMP142738\\Desktop\\New folder\\Readers Quick Ref Card.pdf");
    byte[] src = new Abc().readFileAsString(filePath);
    byte[] destination = Base64.encode(src);

   }

問題出在你的流程中

byte[] -> String -> base64 string

您需要省略到String的轉換並直接進行:

byte[] -> base64 string

轉換為String會破壞二進制流,因為它涉及從輸入字符集到16位Unicode字符的解碼操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM