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 (Binary File)를 변환 할 수 있지만 파일이 손상/손상되었습니다. 또한 전체 프로세스 (Encode-Decode) 후의 출력 파일은 입력 파일보다 훨씬 큽니다. 나는 둘 다 같은 크기가 될 것으로 예상했다. 여기서 내가 뭘 잘못하고 있니?왜 Java에서 byte []의 Base64 인코딩이 작동하지 않습니까?
편집 1 (7/13/16) : 주 방법에서 Jim의 제안에 따라 코드를 수정했습니다. 동일한 문서를 읽은 후에 Base64.encode (byte [] src)를 사용해 보았습니다. 그러나 "Base64.encode (byte []) 기호를 찾을 수 없습니다."라는 오류 메시지가 계속 표시됩니다. 하지만 동일한 클래스 (java.util.Base64.Encoder)에서 encodetoString 메서드를 사용했습니다. 여기서 문제를 이해할 수 없습니다. 다음은 readFileAsString 메소드에서 byte []를 반환 한 후 수정 된 main 메소드입니다.
byte[] -> base64 string
을 바이너리 스트림은 손상이 포함되므로 문자열로 변환 :
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);
}
이 질문을 작성할 때 어떤 이유로'main()'에서 사용하고있는''Zul' 클래스가'Abc'로 이름이 변경되었다고 가정합니다. 'encodeToString()'은 매개 변수로'byte []'을 취하기 때문에 불필요하게 새로운'String()'을 생성하는 대신'readFileAsString()'에서'byte []' '그냥 그것을 버리기위한 객체. 100 % 확신 할 수는 없지만 UTF-8로 'String'을 만드는 것이 문제의 원인 일 수 있다고 생각합니다. 다만 추측, 시험하지 않으며 근원이 없다. 또한,'readFileAsString()'이 정적이기 때문에'Abc.readFileAsString()'을 할 수 있습니다. – jonhopkins