관리 메뉴

IT.FARMER

java Byte[] 문자열 변환 및 복원 본문

JAVA

java Byte[] 문자열 변환 및 복원

아이티.파머 2021. 6. 1. 10:36
반응형

byte[] 배열을 문자열로 변환하여 사용

RestAPI 통신을 하거나, 혹은 다른 이유로 인해서 파일을(Byte[]) 를 문자열로 저장 하거나 보내야할 경우가 있다.
가끔 우리가 웹화면에서 HTML의 image 테그를 이용할때 <image=base64/.... 으로 시작되는걸 보았을텐데 이또한 문자열로 가지고 있다가 이미지로 변환을 해준다.( 지금으로 부터 5~6년전에 사용했던거 같다. )

Byte 배열로 되어 있는 파일을 RDB에 저장할 때도 이전엔 Clob, Blob 타입으로 저장 하기도한다.
여기 예제에서는 이미지나 문자열을 Byte로 변환하고 다시 문자열/이미지로 복원하는 방법이다.
위에 언급했듯이 웹API 통신시 파일을 주고 받을때 사용하면 유용하다.

  • 기본적으로 java 에서는 new String(byte[],charset) 으로 byte 를 문자열로 변경 할 수 있다.
  • Byte를 문자열로 보관할때는 Base64로 인코딩하여 보관하는게 안전하다.

예제

public class FileByteStream {


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

        FileByteStream.stringByteStream();;
        FileByteStream.imageFileStream();

    }

    public static void stringByteStream () {
        String textStr = "Hello World";
        byte[] bytes = textStr.getBytes();

        System.out.printf("original plain  text %s  \n", textStr);
        System.out.printf("bytes convert %s  \n", (Object) bytes);
        System.out.printf("bytes format > toString %s  \n", bytes.toString());

        String data = new String(bytes, StandardCharsets.UTF_8);
        System.out.println("byte array decoding = " + data);
    }

    public static void imageFileStream() throws IOException {
        String filePath = "C:\\Users\\skan\\Downloads\\urbanbrush-20200528234654335659.jpg";
        byte[] imageBytes = Files.readAllBytes(Paths.get(filePath));

        String  str =  Base64.getEncoder().encodeToString(imageBytes);
        System.out.println(str);

        byte[] imageDecode = Base64.getDecoder().decode(str);


        Files.write(Paths.get("C:\\Users\\skan\\Downloads\\ssadasd.jpg"), imageDecode);

    }
}
반응형

'JAVA' 카테고리의 다른 글

java URL stream meta data 추출  (0) 2021.06.09
java generic 사용법  (0) 2021.06.01
remote debuging intelliJ  (0) 2021.04.29
FetureTask  (0) 2021.04.02
ArrayBlockingQueue  (0) 2021.01.15