InputStream 을 String 으로 변환하기

JavaBeginner
지금 연습하기

소개

Java 에서 InputStream 클래스는 파일에서 데이터를 순차적으로 읽는 데 사용됩니다. 데이터를 문자열로 사용하려면 InputStream 을 String 으로 변환해야 합니다. 이 랩에서는 InputStream 을 문자열로 변환하는 다양한 방법을 배웁니다.

InputStreamReader 사용하기

InputStreamReader 클래스는 InputStream에서 문자 배열로 데이터를 읽는 read() 메서드를 제공합니다. 문자 배열을 문자열로 변환할 수 있습니다. ~/project 디렉토리에 다음 내용으로 새로운 Java 소스 파일 InputStreamToString.java를 생성합니다.

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class InputStreamToString {
    public static String inputStreamToString(InputStream input) throws IOException {
        InputStreamReader reader = new InputStreamReader(input);
        char[] charArray = new char[256];
        reader.read(charArray);
        return new String(charArray);
    }

    public static void main(String[] args) {
        try {
            InputStream input = new ByteArrayInputStream("hello world".getBytes());
            String strFromInputStream = inputStreamToString(input);
            System.out.print("String from the Input Stream is: " + strFromInputStream);
        } catch(Exception e) {
            System.out.print(e);
        }
    }
}

코드를 실행하려면 터미널을 열고 다음 명령으로 코드를 컴파일하고 실행합니다.

javac InputStreamToString.java && java InputStreamToString

InputStreamReader, BufferedReader 및 StringBuilder 사용하기

이전 단계는 더 큰 입력에 대해 비효율적일 수 있습니다. 대신, 효율성을 높이기 위해 InputStreamReader를 래핑하는 BufferedReader를 사용할 수 있습니다. 그런 다음 StringBuilder 객체를 사용하여 BufferedReader에서 읽은 줄을 추가합니다. InputStreamToString.java에서 Step 1 다음에 다음 코드로 새로운 단계를 생성합니다.

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class InputStreamToString {
    public static String inputStreamToString(InputStream input) throws IOException {
        StringBuilder builder = new StringBuilder();
        InputStreamReader reader = new InputStreamReader(input);
        BufferedReader bufferedReader = new BufferedReader(reader);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            builder.append(line);
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        try {
            InputStream input = new ByteArrayInputStream("hello world".getBytes());
            String strFromInputStream = inputStreamToString(input);
            System.out.print("String from the Input Stream is: " + strFromInputStream);
        } catch(Exception e) {
            System.out.print(e);
        }
    }
}

StringBuilder 없이 InputStreamReader 및 BufferedReader 사용하기

BufferedReader 클래스의 lines() 메서드를 사용하여 더 간단한 접근 방식을 사용할 수 있습니다. 이렇게 하면 각 줄을 별도의 StringBuilder 인스턴스에 추가하는 단계를 건너뛸 수 있습니다. InputStreamToString.java에서 Step 2 다음에 다음 코드로 새로운 단계를 생성합니다.

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

public class InputStreamToString {
    public static String inputStreamToString(InputStream input) throws IOException {
        InputStreamReader reader = new InputStreamReader(input);
        BufferedReader bufferedReader = new BufferedReader(reader);
        String str = bufferedReader.lines().collect(Collectors.joining("\n"));
        return str;
    }

    public static void main(String[] args) {
        InputStream input = new ByteArrayInputStream("hello world".getBytes());
        String strFromInputStream = inputStreamToString(input);
        System.out.print("String from the Input Stream is: " + strFromInputStream);
    }
}

InputStream 의 readAllBytes() 메서드 사용법

Java 9에서 InputStream 클래스는 readAllBytes() 메서드를 도입했습니다. 이 메서드는 전체 InputStream 객체를 한 줄의 코드로 효율적으로 문자열로 변환할 수 있습니다. 하지만 이 메서드는 더 큰 입력에는 권장되지 않습니다. InputStreamToString.java에서 Step 3 다음에 다음 코드로 새로운 단계를 생성합니다.

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamToString {
    public static String inputStreamToString(InputStream input) throws IOException {
        return new String(input.readAllBytes());
    }

    public static void main(String[] args) {
        try {
            InputStream input = new ByteArrayInputStream("hello world".getBytes());
            String strFromInputStream = inputStreamToString(input);
            System.out.print("String from the Input Stream is: " + strFromInputStream);
        } catch(Exception e) {
            System.out.print(e);
        }
    }
}

Scanner 클래스 사용법

입력 스트림을 문자열로 변환하기 위해 데이터 읽기 및 파싱에 일반적으로 사용되는 Scanner 클래스를 사용할 수도 있습니다. InputStreamToString.java에서 Step 4 다음에 다음 코드로 새로운 단계를 생성합니다.

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

public class InputStreamToString {
    public static String inputStreamToString(InputStream input) throws IOException {
        Scanner scanner = new Scanner(input);
        StringBuilder builder = new StringBuilder();
        while (scanner.hasNext()) {
            builder.append(scanner.nextLine());
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        try {
            InputStream input = new ByteArrayInputStream("hello world".getBytes());
            String strFromInputStream = inputStreamToString(input);
            System.out.print("String from the Input Stream is: " + strFromInputStream);
        } catch(Exception e) {
            System.out.print(e);
        }
    }
}

ByteArrayOutputStream 사용 방법

java.io 패키지의 ByteArrayOutputStream 클래스를 사용하여 입력 스트림에서 바이트 배열로 데이터를 복사할 수 있습니다. 그런 다음 바이트 배열을 ByteArrayOutputStream에 쓸 수 있습니다. 마지막으로, ByteArrayOutputStream의 toString() 메서드를 사용하여 문자열 표현을 얻습니다. InputStreamToString.java에서 Step 5 다음에 다음 코드로 새로운 단계를 생성합니다.

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamToString {
    public static String inputStreamToString(InputStream input) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[128];
        int length;
        while ((length = input.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, length);
        }
        return byteArrayOutputStream.toString();
    }

    public static void main(String[] args) {
        try {
            InputStream input = new ByteArrayInputStream("hello world".getBytes());
            String strFromInputStream = inputStreamToString(input);
            System.out.print("String from the Input Stream is: " + strFromInputStream);
        } catch(Exception e) {
            System.out.print(e);
        }
    }
}

java.nio 패키지 사용법

java.nio 패키지에서 Files.createTempFile을 사용하여 임시 파일을 생성하고 InputStream에서 이 파일로 데이터를 복사할 수 있습니다. 그런 다음 이 임시 파일의 내용을 문자열로 읽을 수 있습니다. InputStreamToString.java에서 Step 6 다음에 다음 코드로 새로운 단계를 생성합니다.

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class InputStreamToString {
    public static String inputStreamToString(InputStream input) throws IOException {
        Path file = Files.createTempFile(null, null);
        Files.copy(input, file, StandardCopyOption.REPLACE_EXISTING);
        return new String(Files.readAllBytes(file));
    }

    public static void main(String[] args) {
        try {
            InputStream input = new ByteArrayInputStream("hello world".getBytes());
            String strFromInputStream = inputStreamToString(input);
            System.out.print("String from the Input Stream is: " + strFromInputStream);
        } catch(Exception e) {
            System.out.print(e);
        }
    }
}

Google Guava 라이브러리 사용 방법

Google Guava 라이브러리는 InputStream을 문자열로 변환하기 위한 CharStreams 클래스를 제공합니다. 이 클래스의 toString() 메서드를 사용하여 이를 수행할 수 있습니다. 이 메서드는 Readable 객체 (예: InputStreamReader) 를 받아 데이터를 문자열로 읽습니다. InputStreamToString.java에서 Step 7 다음에 다음 코드로 새로운 단계를 생성합니다.

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.google.common.io.CharStreams;

public class InputStreamToString {
    public static String inputStreamToString(InputStream input) throws IOException {
        try(InputStreamReader reader = new InputStreamReader(input)) {
            return CharStreams.toString(reader);
        }
    }

    public static void main(String[] args) {
        try {
            InputStream input = new ByteArrayInputStream("hello world".getBytes());
            String strFromInputStream = inputStreamToString(input);
            System.out.print("String from the Input Stream is: " + strFromInputStream);

        } catch(Exception e) {
            System.out.print(e);
        }
    }
}

Apache Commons IO 사용법

org.apache.commons.io 패키지의 IOUtils 클래스에도 toString() 메서드가 포함되어 있습니다. InputStream 객체를 이 메서드에 직접 전달할 수 있으며, 이 메서드는 해당 객체에서 데이터를 읽어 문자열로 변환합니다. 또한 Charset을 지정해야 합니다. InputStreamToString.java에서 Step 8 다음에 다음 코드로 새로운 단계를 생성합니다.

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;

public class InputStreamToString {
    public static void main(String[] args) {
        try {
            InputStream input = new ByteArrayInputStream("hello world".getBytes());
            String strFromInputStream = IOUtils.toString(input, StandardCharsets.UTF_8.name());
            System.out.print("String from the Input Stream is: " + strFromInputStream);

        } catch(Exception e) {
            System.out.print(e);
        }
    }
}

Apache Commons IO 와 StringWriter 클래스 활용 방법

java.io 패키지의 StringWriter 클래스를 사용하여 InputStream의 내용을 StringWriter에 복사할 수 있습니다. IOUtils 클래스의 copy() 메서드를 사용할 것입니다. InputStreamToString.java에서 Step 9 다음에 다음 코드로 새로운 단계를 생성합니다.

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;

public class InputStreamToString {
    public static void main(String[] args) {
        try {
            InputStream input = new ByteArrayInputStream("hello world".getBytes());
            StringWriter sw = new StringWriter();
            IOUtils.copy(input, sw, StandardCharsets.UTF_8.name());
            String strFromInputStream = sw.toString();
            System.out.print("String from the Input Stream is: " + strFromInputStream);

        } catch(Exception e) {
            System.out.print(e);
        }
    }
}

요약

이 랩에서는 Java 에서 InputStream을 문자열로 변환하는 다양한 방법을 배웠습니다. 효율성을 높이기 위해 ByteArrayOutputStream 또는 BufferedReader 클래스를 사용할 수 있습니다. Scanner 클래스도 입력 스트림을 문자열로 변환하는 데 사용할 수 있습니다. readAllBytes() 메서드는 작은 입력에만 적합합니다. Google Guava 또는 Apache Commons IO 와 같은 외부 라이브러리를 사용하여 프로세스를 단순화할 수 있습니다. 예외를 처리하고 InputStream을 닫아 리소스 누수를 방지하는 것을 잊지 마십시오.