[Java] InputStream 을 String(문자열)로 변환하는 방법

식빵·2023년 6월 21일
0

Java Lab

목록 보기
12/23
post-thumbnail

별거 아닌데 계속 사용법을 까먹어서 기록해둡니다.


방법 (1)

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class Test {

    public static void main(String[] args) {

        try (InputStream inputStream = resource.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))
        ){
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            System.out.println("text = " + stringBuilder.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}



방법 (2)

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class Test {

    public static void main(String[] args) {

        try ( BufferedReader reader = new BufferedReader(new InputStreamReader(resource))) {
            String str = reader.lines().collect(Collectors.joining("\n"));
            System.out.println("text = " + str);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}



방법 (3)

jdk 9 이상에서만 가능한 방법입니다. 유의하시기 바랍니다.

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class Test {

    public static void main(String[] args) {

        try (InputStream is = Test.class.getResourceAsStream("/throughput/book.txt")) {
        	// readAllBytes 은 jdk 9 이상에서만 제공합니다!
            String text = new String(is.readAllBytes(), StandardCharsets.UTF_8);
            System.out.println("text = " + text);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}



방법 (4)

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Test {

    public static void main(String[] args) {

        try (InputStream is = Test.class.getResourceAsStream("/throughput/book.txt")) {
            byte[] buffer = new byte[8912];
            int readLen;
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            while ((readLen = is.read(buffer)) >= 0) {
                os.write(buffer, 0, readLen);
            }

            String text = "";

            // jdk 10 이상
            // String text = os.toString(StandardCharsets.UTF_8);

            // jdk 10 이전
            String text = new String(os.toByteArray(), StandardCharsets.UTF_8);
            
            System.out.println("text = " + text);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}



방법 (5)

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Test {

    public static void main(String[] args) {

        try (InputStream is = Test.class.getResourceAsStream("/throughput/book.txt");
             Scanner scanner = new Scanner(is, StandardCharsets.UTF_8)) {
        
            StringBuilder sb = new StringBuilder();
            scanner.useDelimiter("\\\\n").forEachRemaining(sb::append);
            System.out.println("text = " + sb);
            
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}



방법 (6) IOUtils 사용

maven commons-io:common-io 아키텍쳐에 있습니다.

import org.apache.commons.io.IOUtils;

private String readEmailHtmlTemplate() {
    try (InputStream is = resourceFile.getInputStream()){
        return IOUtils.toString(is, StandardCharsets.UTF_8);
    } catch (IOException e) {
        log.error("error while reading text in file", e);
    }
}



방법 (7) Spring 유틸 : FileCopyUtils 사용

import org.springframework.util.FileSystemUtils;

private String readEmailHtmlTemplate() {
	try (Reader rd 
    	= new InputStreamReader(resourceFile.getInputStream(), StandardCharsets.UTF_8)
	){
        return FileCopyUtils.copyToString(rd);
    } catch (IOException e) {
        log.error("error while reading text in file", e);
    }
}



이외의 다양한 방법들

profile
백엔드를 계속 배우고 있는 개발자입니다 😊

0개의 댓글