본문 바로가기
IT/JAVA

[JAVA] 가끔 써먹을 base64 인코딩 전용 메서드 생성.

by 쫄보에서고수까지 2021. 12. 22.
반응형

Java에서 File 이미지 데이터를  Base64 인코딩을 위한 아주 간단한 메서드를 기록(?) 공유 하고자 한다.

fileToString(file 데이터만 넘겨주면 끝.

  public String fileToString(File file) {
            String fileString = new String();
            FileInputStream inputStream = null;
            ByteArrayOutputStream byteOutStream = null;
            try {
                inputStream = new FileInputStream(file);
                int len = 0;
                byte[] buf = new byte[1024];
                while ((len = inputSteam.read(buf)) != -1) {
                    byteOutSteam.write(buf, 0, len);
                }
                byte[] fileArray = byteOutSteam.toByteArray();
                fileString = new String(Base64.encodeBase64(fileArray));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    inputSteam.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    byteOutSteam.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return fileString;
            
        }
 
File -> Binary Data -> Base64 encode -> String 반환.
 
필요 import 
 
import org.apache.commons.codec.binary.Base64;
import java.io.*;

 org.apache.commons.codec.binary.Base64 가 아니면
 
Base64.encodeBase64  사용이 불가하다.
 
반응형
LIST

댓글