티스토리 뷰

요즘은 보안문제 이슈로 인해 파일을 주고 받을 때 스트림 방식이 아닌 Base64로 인코딩하여 스트링 형식으로 변환하여 주고 받는 방식을 많이 사용하고 있다. 그러면 자바에서는 어떻게 구현하면 되는것일까? 


대체적으로 파일을 다운로드 받을 때는 OutputStream에 파일을 쓰는데, String형으로 변환을 하기 위해서는 byteOutputStream에 파일을 쓰고 바이트배열형식으로 형을 변환하여 Base64로 인코딩하면 쉽게 String형으로 파일을 변환할 수 있다. 


이는 파일 사이즈가 작고 모바일 통신에서 주로 사용하는 방식으로 String형으로 변환된 파일을 XML에 포함으로 주고 받기도 한다. 


아래 소스는 파일을 다운로드 받을 때 파일을 Base64로 인코딩하여 String 형으로 변환하는 메소드 예제이다.

//상단에 Base64 처리를 하기 위해 import 한다.

import org.apache.commons.codec.binary.Base64


//파일을 Base64로 인코딩하여 String형으로 변환하는 메소드

public String fileToString(File file) {

    String fileString = new String();

    FileInputStream inputStream =  null;

    ByteArrayOutputStream byteOutStream = null;


    try {

        inputStream = new FileInputStream(file);

byteOutStream = new ByteArrayOutputStream();

    

int len = 0;

byte[] buf = new byte[1024];

        while ((len = inputStream.read(buf)) != -1) {

             byteOutStream.write(buf, 0, len);

        }


        byte[] fileArray = byteOutStream.toByteArray();

        fileString = new String(Base64.encodeBase64(fileArray));

        

    } catch (IOException e) {

        e.printStackTrace();

    } finally {

nputStream.close();

        byteOutStream.close();

    }

    return fileString;

}



최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함