CORE
HOME > JAVA > J2SE > CORE
2020.10.03 / 18:10

print - java ioutils string to inputstream

Ãß¼®µ¹ÀÌ
Ãßõ ¼ö 253

Java¿¡¼­ InputStreamÀ» StringÀ¸·Î Àаųª º¯È¯ÇÏ´Â ¹æ¹ýÀº ¹«¾ùÀԴϱî? (20)

java.io.InputStream °´Ã¼°¡ ÀÖ´Ù¸é ±× °´Ã¼¸¦ ¾î¶»°Ô ó¸®ÇÏ°í String »ý¼ºÇؾßÇմϱî?

ÅؽºÆ® µ¥ÀÌÅ͸¦ Æ÷ÇÔÇϴ InputStream ÀÌ ÀÖ´Ù°í °¡Á¤ÇÏ°íÀ̸¦ String À¸·Î º¯È¯ÇÏ·Á°íÇÕ´Ï´Ù. ¿¹¸¦ µé¾îÀ̸¦ ·Î±× ÆÄÀÏ¿¡ ¾µ ¼ö ÀÖ½À´Ï´Ù.

InputStream À» °¡Á® ¿Í¼­ String º¯È¯ÇÏ´Â °¡Àå ½¬¿î ¹æ¹ýÀº ¹«¾ùÀԴϱî?

public String convertStreamToString(InputStream is) { 
    // ???
}

Apache Commons´Â ´ÙÀ½À» Çã¿ëÇÕ´Ï´Ù.

String myString = IOUtils.toString(myInputStream, "UTF-8");

¹°·Ð UTF-8 ¿Ü¿¡µµ ´Ù¸¥ ¹®ÀÚ ÀÎÄÚµùÀ» ¼±ÅÃÇÒ ¼ö ÀÖ½À´Ï´Ù.

ÂüÁ¶ : ( Docs )


Google Collections / Guava¸¦ »ç¿ëÇÏ´Â °æ¿ì ´ÙÀ½À» ¼öÇà ÇÒ ¼ö ÀÖ½À´Ï´Ù.

InputStream stream = ...
String content = CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8));
Closeables.closeQuietly(stream);

InputStreamReader ÀÇ µÎ ¹ø° ¸Å°³ º¯¼ö (¿¹ : Charsets.UTF_8)´Â ÇÊ¿äÇÏÁö ¾ÊÁö¸¸, ¾Ë°í ÀÖ´Ù¸é ÀÎÄÚµùÀ» ÁöÁ¤ÇÏ´Â °ÍÀÌ ÁÁ½À´Ï´Ù.


³ª´Â 14 °¡ÁöÀÇ ÇØ´äÀ» Á¦½ÃÇß´Ù. (Å©·¹µ÷À» Á¦°øÇÏÁö ¸øÇØ ¹Ì¾ÈÇÏÁö¸¸ ³Ê¹« ¸¹Àº Áߺ¹ÀÌÀÖ´Ù)

°á°ú´Â ¸Å¿ì ³î¶ø½À´Ï´Ù. Apache IOUtils °¡ °¡Àå ´À¸®°í ByteArrayOutputStream ÀÌ °¡Àå ºü¸¥ ¼Ö·ç¼ÇÀÔ´Ï´Ù.

¸ÕÀú ¿©±â¿¡ °¡Àå ÁÁÀº ¹æ¹ýÀÌ ÀÖ½À´Ï´Ù.

public String inputStreamToString(InputStream inputStream) throws IOException {
    try(ByteArrayOutputStream result = new ByteArrayOutputStream()) {
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }

        return result.toString(UTF_8);
    }
}

20 »çÀÌŬÀÇ 20MB ÀÓÀÇ ¹ÙÀÌÆ®ÀÇ º¥Ä¡ ¸¶Å© °á°ú

¹Ð¸® ÃÊ ´ÜÀ§ÀÇ ½Ã°£

  • ByteArrayOutputStreamTest : 194
  • NioStream : 198
  • Java9ISTransferTo : 201
  • Java9ISReadAllBytes : 205
  • BufferedInputStreamVsByteArrayOutputStream : 314
  • ApacheStringWriter2 : 574
  • GuavaCharStreams : 589
  • ScannerReaderNoNextTest : 614
  • ScannerReader : 633
  • ApacheStringWriter : 1544
  • StreamApi : ¿À·ù
  • ParallelStreamApi : ¿À·ù
  • BufferReaderTest : ¿À·ù
  • InputStreamAndStringBuilder : ¿À·ù

º¥Ä¡ ¸¶Å© ¼Ò½º ÄÚµå

import com.google.common.io.CharStreams;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * Created by Ilya Gazman on 2/13/18.
 */
public class InputStreamToString {


    private static final String UTF_8 = "UTF-8";

    public static void main(String... args) {
        log("App started");
        byte[] bytes = new byte[1024 * 1024];
        new Random().nextBytes(bytes);
        log("Stream is ready\n");

        try {
            test(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void test(byte[] bytes) throws IOException {
        List<Stringify> tests = Arrays.asList(
                new ApacheStringWriter(),
                new ApacheStringWriter2(),
                new NioStream(),
                new ScannerReader(),
                new ScannerReaderNoNextTest(),
                new GuavaCharStreams(),
                new StreamApi(),
                new ParallelStreamApi(),
                new ByteArrayOutputStreamTest(),
                new BufferReaderTest(),
                new BufferedInputStreamVsByteArrayOutputStream(),
                new InputStreamAndStringBuilder(),
                new Java9ISTransferTo(),
                new Java9ISReadAllBytes()
        );

        String solution = new String(bytes, "UTF-8");

        for (Stringify test : tests) {
            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes)) {
                String s = test.inputStreamToString(inputStream);
                if (!s.equals(solution)) {
                    log(test.name() + ": Error");
                    continue;
                }
            }
            long startTime = System.currentTimeMillis();
            for (int i = 0; i < 20; i++) {
                try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes)) {
                    test.inputStreamToString(inputStream);
                }
            }
            log(test.name() + ": " + (System.currentTimeMillis() - startTime));
        }
    }

    private static void log(String message) {
        System.out.println(message);
    }

    interface Stringify {
        String inputStreamToString(InputStream inputStream) throws IOException;

        default String name() {
            return this.getClass().getSimpleName();
        }
    }

    static class ApacheStringWriter implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            StringWriter writer = new StringWriter();
            IOUtils.copy(inputStream, writer, UTF_8);
            return writer.toString();
        }
    }

    static class ApacheStringWriter2 implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            return IOUtils.toString(inputStream, UTF_8);
        }
    }

    static class NioStream implements Stringify {

        @Override
        public String inputStreamToString(InputStream in) throws IOException {
            ReadableByteChannel channel = Channels.newChannel(in);
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 16);
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            WritableByteChannel outChannel = Channels.newChannel(bout);
            while (channel.read(byteBuffer) > 0 || byteBuffer.position() > 0) {
                byteBuffer.flip();  //make buffer ready for write
                outChannel.write(byteBuffer);
                byteBuffer.compact(); //make buffer ready for reading
            }
            channel.close();
            outChannel.close();
            return bout.toString(UTF_8);
        }
    }

    static class ScannerReader implements Stringify {

        @Override
        public String inputStreamToString(InputStream is) throws IOException {
            java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
            return s.hasNext() ? s.next() : "";
        }
    }

    static class ScannerReaderNoNextTest implements Stringify {

        @Override
        public String inputStreamToString(InputStream is) throws IOException {
            java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
            return s.next();
        }
    }

    static class GuavaCharStreams implements Stringify {

        @Override
        public String inputStreamToString(InputStream is) throws IOException {
            return CharStreams.toString(new InputStreamReader(
                    is, UTF_8));
        }
    }

    static class StreamApi implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            return new BufferedReader(new InputStreamReader(inputStream))
                    .lines().collect(Collectors.joining("\n"));
        }
    }

    static class ParallelStreamApi implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            return new BufferedReader(new InputStreamReader(inputStream)).lines()
                    .parallel().collect(Collectors.joining("\n"));
        }
    }

    static class ByteArrayOutputStreamTest implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            try(ByteArrayOutputStream result = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) != -1) {
                    result.write(buffer, 0, length);
                }

                return result.toString(UTF_8);
            }
        }
    }

    static class BufferReaderTest implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            String newLine = System.getProperty("line.separator");
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder result = new StringBuilder(UTF_8);
            String line;
            boolean flag = false;
            while ((line = reader.readLine()) != null) {
                result.append(flag ? newLine : "").append(line);
                flag = true;
            }
            return result.toString();
        }
    }

    static class BufferedInputStreamVsByteArrayOutputStream implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            ByteArrayOutputStream buf = new ByteArrayOutputStream();
            int result = bis.read();
            while (result != -1) {
                buf.write((byte) result);
                result = bis.read();
            }

            return buf.toString(UTF_8);
        }
    }

    static class InputStreamAndStringBuilder implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            int ch;
            StringBuilder sb = new StringBuilder(UTF_8);
            while ((ch = inputStream.read()) != -1)
                sb.append((char) ch);
            return sb.toString();
        }
    }

    static class Java9ISTransferTo implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            inputStream.transferTo(bos);
            return bos.toString(UTF_8);
        }
    }

    static class Java9ISReadAllBytes implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            return new String(inputStream.readAllBytes(), UTF_8);
        }
    }

}

³ª´Â ÀÚ¹Ù 8 Æ®¸¯À» »ç¿ëÇÑ´Ù.

public static String streamToString(final InputStream inputStream) throws Exception {
    // buffering optional
    try
    (
        final BufferedReader br
           = new BufferedReader(new InputStreamReader(inputStream))
    ) {
        // parallel optional
        return br.lines().parallel().collect(Collectors.joining("\n"));
    } catch (final IOException e) {
        throw new RuntimeException(e);
        // whatever.
    }
}

±âº»ÀûÀ¸·Î ´õ °£°áÇÑ °ÍÀ» Á¦¿ÜÇÏ°í´Â ´Ù¸¥ ´äº¯°ú °°½À´Ï´Ù.


´ÙÀ½Àº ¸î °¡Áö ½ÇÇèÀ» ÅëÇØ ³ª¿Ô´ø °¡Àå ¿ì¾ÆÇÏ°í ¼ø¼öÇÑ Java (¶óÀ̺귯¸® ¾øÀ½) ¼Ö·ç¼ÇÀÔ´Ï´Ù.

public static String fromStream(InputStream in) throws IOException
{
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder out = new StringBuilder();
    String newLine = System.getProperty("line.separator");
    String line;
    while ((line = reader.readLine()) != null) {
        out.append(line);
        out.append(newLine);
    }
    return out.toString();
}

´ÙÀ½Àº Ç¥ÁØ Java ¶óÀ̺귯¸® ¸¸ »ç¿ëÇÏ´Â ¹æ¹ýÀÔ´Ï´Ù (½ºÆ®¸²ÀÌ ´ÝÈ÷Áö ¾Ê¾Ò½À´Ï´Ù. YMMV).

static String convertStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

³ª´Â "¹Ùº¸ °°Àº ½ºÄ³³Ê ¼ÓÀÓ¼ö" ±â»ç¿¡¼­ÀÌ Æ®¸¯À» ¹è¿ü´Ù. ±× ÀÌÀ¯´Â Scanner °¡ ½ºÆ®¸²¿¡¼­ ÅäÅ«À» ¹Ýº¹Çϱ⠶§¹®ÀÔ´Ï´Ù.ÀÌ °æ¿ì ¿ì¸®´Â "ÀÔ·Â °æ°èÀÇ ½ÃÀÛ"(\ A)À» »ç¿ëÇÏ¿© ÅäÅ«À» ºÐ¸®ÇϹǷΠ½ºÆ®¸²ÀÇ Àüü ³»¿ë¿¡ ´ëÇØ ÇϳªÀÇ ÅäÅ« ¸¸ Á¦°øÇÕ´Ï´Ù.

ÀÔ·Â ½ºÆ®¸²ÀÇ ÀÎÄÚµù¿¡ ´ëÇØ ±¸Ã¼ÀûÀ¸·Î ¼³¸í ÇÒ ÇÊ¿ä°¡ÀÖ´Â °æ¿ì, »ç¿ëÇϴ ij¸¯ÅÍ ¼¼Æ® ( ¡¸UTF-8¡¹µî)¸¦ ³ªÅ¸³»´Â 2 ¹ø°ÀÇ Àμö¸¦ Scanner »ý¼ºÀÚ¿¡ Á¦°ø ÇÒ ¼ö ÀÖ½À´Ï´Ù.

¸ðÀÚ ÆÁÀº Á¦°Ô ¾ð±Þ ÇÑ ±â»ç¸¦ ÇÑ ¹ø ÁöÀûÇÑ Jacob, ¿¡°Ô °£´Ù.

EDITED : Patrick ÀÇ Á¦¾È ´öºÐ¿¡ ºó ÀÔ·Â ½ºÆ®¸²À» ó¸® ÇÒ ¶§ ±â´ÉÀÌ ´õ¿í °­·Â ÇØÁ³ ½À´Ï´Ù. ÇÑ ¹ø ´õ ÆíÁý : nixed try / catch, PatrickÀÇ ¹æ¹ýÀº °£°áÇÕ´Ï´Ù.


¾î¶§?

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

public static String readInputStreamAsString(InputStream in) 
    throws IOException {

    BufferedInputStream bis = new BufferedInputStream(in);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    int result = bis.read();
    while(result != -1) {
      byte b = (byte)result;
      buf.write(b);
      result = bis.read();
    }        
    return buf.toString();
}

ÀÌ°ÍÀº ³» ¼ø¼ö ÀÚ¹Ù ¹× ¾Èµå·ÎÀÌµå ¼Ö·ç¼Ç, Àß ÀÛµ¿ÇÕ´Ï´Ù ...

public String readFullyAsString(InputStream inputStream, String encoding)
        throws IOException {
    return readFully(inputStream).toString(encoding);
}    

public byte[] readFullyAsBytes(InputStream inputStream)
        throws IOException {
    return readFully(inputStream).toByteArray();
}    

private ByteArrayOutputStream readFully(InputStream inputStream)
        throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length = 0;
    while ((length = inputStream.read(buffer)) != -1) {
        baos.write(buffer, 0, length);
    }
    return baos;
}

ÀÌ·¸°ÔÇÏ´Â ÁÁÀº ¹æ¹ýÀº ¾ÆÆÄÄ¡ °øÀ¯ IOUtils ¸¦ »ç¿ëÇÏ¿© InputStream À» StringWriter ·Î º¹»çÇÏ´Â °ÍÀÌ´Ù.

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

¶Ç´Â

// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding); 

¶Ç´Â ½ºÆ®¸²°ú ÀÛ¼ºÀÚ¸¦ ¼¯¾î »ç¿ëÇÏÁö ¾ÊÀ¸·Á¸é ByteArrayOutputStream »ç¿ëÇÒ ¼ö ÀÖ½À´Ï´Ù.


ÆÄÀÏ Çϳª¸¦ °í·ÁÇØ º¼ ¶§ ¸ÕÀú java.io.Reader ÀνºÅϽº¸¦ ¾ò¾î¾ßÇÕ´Ï´Ù. ±×·± ´ÙÀ½À̸¦ Àаí StringBuilder Ãß°¡ ÇÒ ¼ö ÀÖ½À´Ï´Ù (´ÙÁß ½º·¹µå¿¡¼­ ¾×¼¼½ºÇÏÁö ¾Ê´Â °æ¿ì StringBuffer °¡ ÇÊ¿äÇÏÁö ¾ÊÀ¸¸ç StringBuilder °¡ ´õ ºü¸§). ¿©±â¼­ ¿ì¸®°¡ ºí·ÏÀ¸·Î ÀÛ¾÷ÇÑ´Ù´Â °ÍÀº ´Ù¸¥ ¹öÆÛ¸µ ½ºÆ®¸²À» ÇÊ¿ä·ÎÇÏÁö ¾Ê´Â´Ù´Â °ÍÀÔ´Ï´Ù. ºí·Ï Å©±â´Â ·±Å¸ÀÓ ¼º´É ÃÖÀûÈ­¸¦ À§ÇØ ¸Å°³ º¯¼öÈ­µË´Ï´Ù.

public static String slurp(final InputStream is, final int bufferSize) {
    final char[] buffer = new char[bufferSize];
    final StringBuilder out = new StringBuilder();
    try (Reader in = new InputStreamReader(is, "UTF-8")) {
        for (;;) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
    }
    catch (UnsupportedEncodingException ex) {
        /* ... */
    }
    catch (IOException ex) {
        /* ... */
    }
    return out.toString();
}

ÀÚ¹Ù 9 ¼Ö·ç¼ÇÀº ¿©±â ¿Ï¼ºÀ» À§ÇØ :

public static String toString(InputStream input) throws IOException {
    return new String(input.readAllBytes(), StandardCharsets.UTF_8);
}

readAllBytes ´Â ÇöÀç JDK 9 ¸ÞÀÎ Äڵ庣À̽º¿¡ ÀÖÀ¸¹Ç·Î ¸±¸®½º¿¡ Ç¥½Ã µÉ °¡´É¼ºÀÌ ÀÖ½À´Ï´Ù. JDK 9 ½º³À ¼¦ ºôµå¸¦ »ç¿ëÇÏ¿© Áö±Ý ½Ãµµ ÇÒ ¼ö ÀÖ½À´Ï´Ù.


Commons IO (FileUtils / IOUtils / CopyUtils)¸¦ »ç¿ëÇÒ ¼ö ¾ø´Ù¸é BufferedReader¸¦ »ç¿ëÇÏ¿© ÇÑ ÁÙ¾¿ ÆÄÀÏÀ» Àд ¿¹Á¦°¡ ÀÖ½À´Ï´Ù.

public class StringFromFile {
    public static void main(String[] args) /*throws UnsupportedEncodingException*/ {
        InputStream is = StringFromFile.class.getResourceAsStream("file.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(is/*, "UTF-8"*/));
        final int CHARS_PER_PAGE = 5000; //counting spaces
        StringBuilder builder = new StringBuilder(CHARS_PER_PAGE);
        try {
            for(String line=br.readLine(); line!=null; line=br.readLine()) {
                builder.append(line);
                builder.append('\n');
            }
        } catch (IOException ignore) { }
        String text = builder.toString();
        System.out.println(text);
    }
}

¶Ç´Â ¿ø½Ã ¼Óµµ¸¦ ¿øÇÑ´Ù¸é Paul de Vrieze°¡ Á¦¾ÈÇÑ ¹Ù¸®¿¡À̼ÇÀ» Á¦¾È ÇÒ °ÍÀÔ´Ï´Ù (ÀÌ´Â StringBuffer¸¦ ³»ºÎÀûÀ¸·Î »ç¿ëÇÏ´Â StringWriter »ç¿ëÀ» ÇÇÇÕ´Ï´Ù).

public class StringFromFileFast {
    public static void main(String[] args) /*throws UnsupportedEncodingException*/ {
        InputStream is = StringFromFileFast.class.getResourceAsStream("file.txt");
        InputStreamReader input = new InputStreamReader(is/*, "UTF-8"*/);
        final int CHARS_PER_PAGE = 5000; //counting spaces
        final char[] buffer = new char[CHARS_PER_PAGE];
        StringBuilder output = new StringBuilder(CHARS_PER_PAGE);
        try {
            for(int read = input.read(buffer, 0, buffer.length);
                    read != -1;
                    read = input.read(buffer, 0, buffer.length)) {
                output.append(buffer, 0, read);
            }
        } catch (IOException ignore) { }

        String text = output.toString();
        System.out.println(text);
    }
}

Kotlin »ç¿ëÀÚ´Â ´Ü¼øÈ÷ ´ÙÀ½À» ¼öÇàÇÕ´Ï´Ù.

println(InputStreamReader(is).readText())

À̹ǷÎ

readText()

Kotlin Ç¥ÁØ ¶óÀ̺귯¸®ÀÇ ³»Àå È®Àå ¸Þ¼ÒµåÀÔ´Ï´Ù.


¶Ç ´Ù¸¥ Çϳª´Â ¸ðµç Spring »ç¿ëÀÚ¸¦À§ÇÑ °ÍÀÔ´Ï´Ù.

import java.nio.charset.StandardCharsets;
import org.springframework.util.FileCopyUtils;

public String convertStreamToString(InputStream is) throws IOException { 
    return new String(FileCopyUtils.copyToByteArray(is), StandardCharsets.UTF_8);
}

¿¡ÀÖ´Â À¯Æ¿¸®Æ¼ ¸Þ¼Òµå´Â org.springframework.util.StreamUtils¿¡¼­¿Í ºñ½Á FileCopyUtilsÇÏÁö¸¸ ¿Ï·áµÇ¸é ½ºÆ®¸²À» ¿­¾î µÓ´Ï´Ù.


½ºÆ®¸² ¸®´õ¸¦ »ç¿ëÇÏ´Â °æ¿ì ³¡¿¡ ½ºÆ®¸²À» ´Ý¾Æ¾ßÇÕ´Ï´Ù.

private String readStream(InputStream iStream) throws IOException {
    //build a Stream Reader, it can read char by char
    InputStreamReader iStreamReader = new InputStreamReader(iStream);
    //build a buffered Reader, so that i can read whole line at once
    BufferedReader bReader = new BufferedReader(iStreamReader);
    String line = null;
    StringBuilder builder = new StringBuilder();
    while((line = bReader.readLine()) != null) {  //Read till end
        builder.append(line);
        builder.append("\n"); // append new line to preserve lines
    }
    bReader.close();         //close all opened stuff
    iStreamReader.close();
    //iStream.close(); //EDIT: Let the creator of the stream close it!
                       // some readers may auto close the inner stream
    return builder.toString();
}

ÆíÁý : JDK 7 +¿¡¼­´Â try-with-resources ±¸Á¶¸¦ »ç¿ëÇÒ ¼öÀÖ´Ù.

/**
 * Reads the stream into a string
 * @param iStream the input stream
 * @return the string read from the stream
 * @throws IOException when an IO error occurs
 */
private String readStream(InputStream iStream) throws IOException {

    //Buffered reader allows us to read line by line
    try (BufferedReader bReader =
                 new BufferedReader(new InputStreamReader(iStream))){
        StringBuilder builder = new StringBuilder();
        String line;
        while((line = bReader.readLine()) != null) {  //Read till end
            builder.append(line);
            builder.append("\n"); // append new line to preserve lines
        }
        return builder.toString();
    }
}

ÀÌ ¶§¹®¿¡ ÁÁ³×¿ä :

  • ¼Õ ¾ÈÀü Charset.
  • Àб⠹öÆÛ Å©±â¸¦ Á¦¾îÇÕ´Ï´Ù.
  • ºô´õÀÇ ±æÀ̸¦ ÇÁ·ÎºñÀú´× ÇÒ ¼ö ÀÖÀ¸¸ç Á¤È®È÷ ÀÛ¼ºÇÒ ¼ö ¾ø½À´Ï´Ù.
  • ¶óÀ̺귯¸® ÀÇÁ¸¼ºÀÌ ¾ø½À´Ï´Ù.
  • ÀÚ¹Ù 7 ÀÌ»óÀÔ´Ï´Ù.

±×°Ô ¹¹¾ß?

public static String convertStreamToString(InputStream is) {
   if (is == null) return null;
   StringBuilder sb = new StringBuilder(2048); // Define a size if you have an idea of it.
   char[] read = new char[128]; // Your buffer size.
   try (InputStreamReader ir = new InputStreamReader(is, StandardCharsets.UTF_8)) {
     for (int i; -1 != (i = ir.read(read)); sb.append(read, 0, i));
   } catch (Throwable t) {}
   return sb.toString();
}

´ÙÀ½ Àº »õ·Î¿î Java API 8 ±â¹Ý ¼Ö·ç¼ÇÀÔ´Ï´Ù.ÀÌ ¼Ö·ç¼ÇÀº »õ·Î¿î Stream API ¸¦ »ç¿ëÇÏ¿© ´ÙÀ½¿¡¼­ ¸ðµç ¶óÀÎÀ» ¼öÁýÇÕ´Ï´Ù InputStream.

public static String toString(InputStream inputStream) {
    BufferedReader reader = new BufferedReader(
        new InputStreamReader(inputStream));
    return reader.lines().collect(Collectors.joining(
        System.getProperty("line.separator")));
}

´ÙÀ½Àº ¹ÙÀÌÆ® ¹è¿­ ¹öÆÛ¸¦ »ç¿ëÇÏ´Â JDK ¸¸ »ç¿ëÇÏ´Â ¹æ¹ýÀÔ´Ï´Ù. ÀÌ°ÍÀº ½ÇÁ¦·Î commons-io IOUtils.copy()¸Þ¼Òµå°¡ ¸ðµÎ ÀÛµ¿ÇÏ´Â ¹æ½ÄÀÔ´Ï´Ù. . ´ë½Å¿¡ º¹»ç byte[]Çϴ char[]°æ¿ì¿¡¸¦ »ç¿ëÇÏ¿© ´ëü ÇÒ ¼ö ÀÖ½À´Ï´Ù .ReaderInputStream

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

...

InputStream is = ....
ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
byte[] buffer = new byte[8192];
int count = 0;
try {
  while ((count = is.read(buffer)) != -1) {
    baos.write(buffer, 0, count);
  }
}
finally {
  try {
    is.close();
  }
  catch (Exception ignore) {
  }
}

String charset = "UTF-8";
String inputStreamAsString = baos.toString(charset);

¿©±â¿¡ º¯È¯ÇÏ´Â ¿Ïº®ÇÑ ¹æ¹ý InputStreamÀ¸·Î StringÁ¦ 3 ÀÚ ¶óÀ̺귯¸®¸¦ »ç¿ëÇÏÁö ¾Ê°í´Â. »ç¿ë StringBuilder´Þ¸® »ç¿ëÇÏ´Â ´ÜÀÏ ½º·¹µå ȯ°æ StringBuffer.

public static String getString( InputStream is) throws IOException {
    int ch;
    StringBuilder sb = new StringBuilder();
    while((ch = is.read()) != -1)
        sb.append((char)ch);
    return sb.toString();
}

ÀÌ°ÍÀº ¾ÆÆÄÄ¡ ±¸ÇöÀ» ¿øÇÏÁö¸¸ Àüü ¶óÀ̺귯¸®¸¦ ¿øÇÏÁö ¾Ê´Â »ç¶÷µéÀ»À§ÇÑ org.apache.commons.io.IOUtils ¼Ò½º Äڵ堿¡¼­ºÎÅÍ ³ª¿Â ´ë´ä ÀÌ´Ù.

private static final int BUFFER_SIZE = 4 * 1024;

public static String inputStreamToString(InputStream inputStream, String charsetName)
        throws IOException {
    StringBuilder builder = new StringBuilder();
    InputStreamReader reader = new InputStreamReader(inputStream, charsetName);
    char[] buffer = new char[BUFFER_SIZE];
    int length;
    while ((length = reader.read(buffer)) != -1) {
        builder.append(buffer, 0, length);
    }
    return builder.toString();
}