Comment lire / convertir un InputStream en une chaîne en Java?


Si vous avez un java.io.InputStream objet, comment devriez-vous traiter cet objet et produire un String?


Supposons que j'ai un InputStream qui contient des données de texte, et je veux le convertir en String, donc par exemple je peux écrire cela dans un fichier journal.

Quel est le moyen le plus simple de prendre le InputStream et de le convertir en String?

public String convertStreamToString(InputStream is) { 
    // ???
}
Author: Steve Chambers, 2008-11-21

30 answers

, Une belle façon de le faire est à l'aide de Apache commons IOUtils pour copier le InputStream en StringWriter... quelque chose comme

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

Ou même

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

Alternativement, vous pouvez utiliser ByteArrayOutputStream si vous ne voulez pas mélanger vos flux et vos auteurs

 2094
Author: Harry Lime, 2018-05-21 13:09:50

Voici un moyen d'utiliser uniquement la bibliothèque Java standard (notez que le flux n'est pas fermé, YMMV).

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

J'ai appris ce truc de "Stupide Scanner astuces" article. La raison pour laquelle cela fonctionne est queScanner itère sur les jetons dans le flux, et dans ce cas, nous séparons les jetons en utilisant "début de la limite d'entrée" (\A) nous donnant ainsi un seul jeton pour tout le contenu du flux.

Remarque, si vous devez être précis sur les flux d'entrée encodage, vous pouvez fournir le deuxième argument au constructeur Scanner qui indique quel jeu de caractères utiliser (par exemple "UTF-8").

Hat Tip va aussi àJacob, qui m'a une fois pointé vers ledit article.

EDITÉ: Grâce à une suggestion de Patrick , a rendu la fonction plus robuste lors de la gestion d'un flux d'entrée vide. Une autre édition: nixed try/catch, la manière de Patrick est plus laconique.

 2125
Author: Pavel Repin, 2017-09-02 01:27:51

Résumer d'autres réponses J'ai trouvé 11 façons principales de le faire (voir ci-dessous). Et j'ai écrit quelques tests de performance (voir les résultats ci-dessous):

Façons de convertir un InputStream en chaîne:

  1. Utiliser IOUtils.toString (Apache Utils)

    String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
    
  2. En utilisant CharStreams (goyave)

    String result = CharStreams.toString(new InputStreamReader(
          inputStream, Charsets.UTF_8));
    
  3. Utiliser Scanner (JDK)

    Scanner s = new Scanner(inputStream).useDelimiter("\\A");
    String result = s.hasNext() ? s.next() : "";
    
  4. En utilisant Stream API (Java 8). Avertissement : Cette solution convertit une ligne différente casse (comme \r\n) en \n.

    String result = new BufferedReader(new InputStreamReader(inputStream))
      .lines().collect(Collectors.joining("\n"));
    
  5. En utilisant API de flux parallèle (Java 8). Warning : Cette solution convertit différents sauts de ligne (comme \r\n) en \n.

    String result = new BufferedReader(new InputStreamReader(inputStream)).lines()
       .parallel().collect(Collectors.joining("\n"));
    
  6. En utilisant InputStreamReader et StringBuilder (JDK)

    final int bufferSize = 1024;
    final char[] buffer = new char[bufferSize];
    final StringBuilder out = new StringBuilder();
    Reader in = new InputStreamReader(inputStream, "UTF-8");
    for (; ; ) {
        int rsz = in.read(buffer, 0, buffer.length);
        if (rsz < 0)
            break;
        out.append(buffer, 0, rsz);
    }
    return out.toString();
    
  7. En utilisant StringWriter et IOUtils.copy (Apache Commons)

    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, "UTF-8");
    return writer.toString();
    
  8. En utilisant ByteArrayOutputStream et inputStream.read (JDK)

    ByteArrayOutputStream result = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) != -1) {
        result.write(buffer, 0, length);
    }
    // StandardCharsets.UTF_8.name() > JDK 7
    return result.toString("UTF-8");
    
  9. En utilisant BufferedReader (JDK). Avertissement: Cette solution convertit différents sauts de ligne (comme \n\r) en propriété système line.separator (par exemple, dans Windows en "\r\n").

    String newLine = System.getProperty("line.separator");
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder result = new StringBuilder();
    String line; boolean flag = false;
    while ((line = reader.readLine()) != null) {
        result.append(flag? newLine: "").append(line);
        flag = true;
    }
    return result.toString();
    
  10. En utilisant BufferedInputStream et ByteArrayOutputStream (JDK)

    BufferedInputStream bis = new BufferedInputStream(inputStream);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    int result = bis.read();
    while(result != -1) {
        buf.write((byte) result);
        result = bis.read();
    }
    // StandardCharsets.UTF_8.name() > JDK 7
    return buf.toString("UTF-8");
    
  11. En utilisant inputStream.read() et StringBuilder (JDK). Avertissement : Cette solution a des problèmes avec Unicode, par exemple avec du texte russe (ne fonctionne correctement qu'avec du texte non Unicode)

    int ch;
    StringBuilder sb = new StringBuilder();
    while((ch = inputStream.read()) != -1)
        sb.append((char)ch);
    reset();
    return sb.toString();
    

Avertissement:

  1. Les solutions 4, 5 et 9 convertissent la ligne différente sauts de à un.

  2. La solution 11 ne peut pas fonctionner correctement avec le texte Unicode

Tests de performance

Tests de performance pour les petits String (longueur = 175), URL dans github (mode= Temps moyen, système = Linux, score 1,343 est le meilleur):

              Benchmark                         Mode  Cnt   Score   Error  Units
 8. ByteArrayOutputStream and read (JDK)        avgt   10   1,343 ± 0,028  us/op
 6. InputStreamReader and StringBuilder (JDK)   avgt   10   6,980 ± 0,404  us/op
10. BufferedInputStream, ByteArrayOutputStream  avgt   10   7,437 ± 0,735  us/op
11. InputStream.read() and StringBuilder (JDK)  avgt   10   8,977 ± 0,328  us/op
 7. StringWriter and IOUtils.copy (Apache)      avgt   10  10,613 ± 0,599  us/op
 1. IOUtils.toString (Apache Utils)             avgt   10  10,605 ± 0,527  us/op
 3. Scanner (JDK)                               avgt   10  12,083 ± 0,293  us/op
 2. CharStreams (guava)                         avgt   10  12,999 ± 0,514  us/op
 4. Stream Api (Java 8)                         avgt   10  15,811 ± 0,605  us/op
 9. BufferedReader (JDK)                        avgt   10  16,038 ± 0,711  us/op
 5. parallel Stream Api (Java 8)                avgt   10  21,544 ± 0,583  us/op

Tests de performance pour big String (longueur = 50100), URL dans github (mode = Temps moyen, système = Linux, score 200,715 est le meilleur):

               Benchmark                        Mode  Cnt   Score        Error  Units
 8. ByteArrayOutputStream and read (JDK)        avgt   10   200,715 ±   18,103  us/op
 1. IOUtils.toString (Apache Utils)             avgt   10   300,019 ±    8,751  us/op
 6. InputStreamReader and StringBuilder (JDK)   avgt   10   347,616 ±  130,348  us/op
 7. StringWriter and IOUtils.copy (Apache)      avgt   10   352,791 ±  105,337  us/op
 2. CharStreams (guava)                         avgt   10   420,137 ±   59,877  us/op
 9. BufferedReader (JDK)                        avgt   10   632,028 ±   17,002  us/op
 5. parallel Stream Api (Java 8)                avgt   10   662,999 ±   46,199  us/op
 4. Stream Api (Java 8)                         avgt   10   701,269 ±   82,296  us/op
10. BufferedInputStream, ByteArrayOutputStream  avgt   10   740,837 ±    5,613  us/op
 3. Scanner (JDK)                               avgt   10   751,417 ±   62,026  us/op
11. InputStream.read() and StringBuilder (JDK)  avgt   10  2919,350 ± 1101,942  us/op

Graphiques (tests de performances en fonction de la longueur du flux d'entrée dans le système Windows 7)
entrez la description de l'image ici

Test de performance (Temps moyen) en fonction de la longueur du flux d'entrée dans le système Windows 7:

 length  182    546     1092    3276    9828    29484   58968

 test8  0.38    0.938   1.868   4.448   13.412  36.459  72.708
 test4  2.362   3.609   5.573   12.769  40.74   81.415  159.864
 test5  3.881   5.075   6.904   14.123  50.258  129.937 166.162
 test9  2.237   3.493   5.422   11.977  45.98   89.336  177.39
 test6  1.261   2.12    4.38    10.698  31.821  86.106  186.636
 test7  1.601   2.391   3.646   8.367   38.196  110.221 211.016
 test1  1.529   2.381   3.527   8.411   40.551  105.16  212.573
 test3  3.035   3.934   8.606   20.858  61.571  118.744 235.428
 test2  3.136   6.238   10.508  33.48   43.532  118.044 239.481
 test10 1.593   4.736   7.527   20.557  59.856  162.907 323.147
 test11 3.913   11.506  23.26   68.644  207.591 600.444 1211.545
 1761
Author: Viacheslav Vedenin, 2018-07-19 02:09:04

Apache Commons permet:

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

Bien sûr, vous pouvez choisir d'autres encodages de caractères que UTF-8.

Voir Aussi: (Docs)

 797
Author: Chinnery, 2016-01-14 00:48:45

En tenant compte du fichier, il faut d'abord obtenir une instance java.io.Reader. Cela peut ensuite être lu et ajouté à un StringBuilder (nous n'avons pas besoin de StringBuffer si nous n'y accédons pas dans plusieurs threads, et StringBuilder est plus rapide). L'astuce ici est que nous travaillons en blocs, et en tant que tels n'ont pas besoin d'autres flux de mise en mémoire tampon. La taille du bloc est paramétrée pour l'optimisation des performances à l'exécution.

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();
}
 266
Author: Paul de Vrieze, 2015-07-15 10:23:45

Que diriez-vous de cela?

InputStream in = /* your InputStream */;
StringBuilder sb=new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String read;

while((read=br.readLine()) != null) {
    //System.out.println(read);
    sb.append(read);   
}

br.close();
return sb.toString();
 228
Author: sampathpremarathna, 2016-01-10 03:58:57

Si vous utilisez Google-Collections/Goyave vous pouvez effectuer les opérations suivantes:

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

Notez que le deuxième paramètre (c'est-à-dire les jeux de caractères.UTF_8) pour le InputStreamReader n'est pas nécessaire, mais c'est généralement une bonne idée de spécifier l'encodage si vous le connaissez (ce que vous devriez!)

 154
Author: Sakuraba, 2013-01-30 16:35:54

Ceci est ma solution Java & Android pure, fonctionne bien...

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;
}
 108
Author: TacB0sS, 2016-03-25 07:54:36

Que diriez-vous de:

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();
}
 56
Author: Jon Moore, 2009-06-10 21:07:11

Voici la solution la plus élégante, pure-Java (pas de bibliothèque) que j'ai trouvée après quelques expérimentations:

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();
}
 55
Author: Drew Noakes, 2013-12-07 16:39:30

Pour être complet, voici Java 9 solution:

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

Le readAllBytes est actuellement dans la base de code principale de JDK 9, il est donc susceptible d'apparaître dans la version. Vous pouvez l'essayer dès maintenant en utilisant le JDK 9 instantané s'appuie.

 43
Author: Tagir Valeev, 2015-09-02 11:50:45

J'utiliserais quelques astuces Java 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.
    }
}

Essentiellement la même chose que d'autres réponses sauf plus succinctes.

 33
Author: Simon Kuang, 2015-07-15 11:03:54

J'ai fait quelques tests de chronométrage parce que le temps compte, toujours.

J'ai tenté d'obtenir la réponse dans une chaîne de 3 manières différentes. (voir ci-dessous)
J'ai laissé de côté les blocs try/catch pour des raisons de lisibilité.

Pour donner du contexte, voici le code précédent pour les 3 approches:

   String response;
   String url = "www.blah.com/path?key=value";
   GetMethod method = new GetMethod(url);
   int status = client.executeMethod(method);

1)

 response = method.getResponseBodyAsString();

2)

InputStream resp = method.getResponseBodyAsStream();
InputStreamReader is=new InputStreamReader(resp);
BufferedReader br=new BufferedReader(is);
String read = null;
StringBuffer sb = new StringBuffer();
while((read = br.readLine()) != null) {
    sb.append(read);
}
response = sb.toString();

3)

InputStream iStream  = method.getResponseBodyAsStream();
StringWriter writer = new StringWriter();
IOUtils.copy(iStream, writer, "UTF-8");
response = writer.toString();

Donc, après avoir exécuté 500 tests sur chaque approche avec les mêmes données de demande / réponse, voici les nombre. Encore une fois, ce sont mes conclusions et vos conclusions ne sont peut-être pas exactement les mêmes, mais j'ai écrit ceci pour donner une indication aux autres des différences d'efficacité de ces approches.

Rang:
Approche # 1
Approche # 3-2,6% plus lente que #1
Approche no 2-4,3% plus lente que #1

L'une de ces approches est une solution appropriée pour saisir une réponse et en créer une chaîne.

 27
Author: Brett Holt, 2017-10-17 08:55:23

Solution Java pure utilisant Stream s, fonctionne depuis Java 8.

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

// ...
public static String inputStreamToString(InputStream is) throws IOException {
    try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
        return br.lines().collect(Collectors.joining(System.lineSeparator()));
    }
}

Tel Que mentionné par Christoffer Hammarström ci-dessous autre réponse, il est plus sûr de spécifier explicitement le Charset. C'est-à-dire que le constructeur InputStreamReader peut être modifié comme suit:

new InputStreamReader(is, Charset.forName("UTF-8"))
 24
Author: czerny, 2017-05-23 12:34:53

J'ai fait un benchmark sur 14 réponses distinctes ici (Désolé de ne pas fournir de crédits mais il y a trop de doublons)

Le résultat est très surprenant. Il s'avère que Apache IOUtils est le plus lent et ByteArrayOutputStream est le plus rapide des solutions:

Voici donc d'abord la meilleure méthode:

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);
    }
}

Résultats de référence, de 20 Mo d'octets aléatoires en 20 cycles

Temps (en millisecondes)

  • ByteArrayOutputStreamTest: 194
  • NioStream: 198
  • Java9ISTransferTo: 201
  • Java9ISReadAllBytes: 205
  • BufferedInputStreamVsByteArrayOutputstream: 314
  • ApacheStringWriter2: 574
  • GuavaCharStreams: 589
  • ScannerReaderNoNextTest: 614
  • ScannerReader: 633
  • ApacheStringWriter: 1544
  • StreamApi: Erreur
  • ParallelStreamApi: Erreur
  • BufferReaderTest: Erreur
  • InputStreamAndStringBuilder: Erreur

Référence code source

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);
        }
    }

}
 24
Author: Ilya Gazman, 2018-02-13 21:30:08

Voici plus ou moins la réponse de sampath, nettoyée un peu et représentée comme une fonction:

String streamToString(InputStream in) throws IOException {
  StringBuilder out = new StringBuilder();
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  for(String line = br.readLine(); line != null; line = br.readLine()) 
    out.append(line);
  br.close();
  return out.toString();
}
 21
Author: TKH, 2012-09-12 18:31:12

Si vous vous sentiez aventureux, vous pourriez mélanger Scala et Java et vous retrouver avec ceci:

scala.io.Source.fromInputStream(is).mkString("")

Mélanger le code et les bibliothèques Java et Scala a ses avantages.

Voir la description complète ici: Moyen idiomatique de convertir un InputStream en chaîne dans Scala

 19
Author: Jack, 2017-05-23 12:18:29

Si vous ne pouvez pas utiliser Commons IO (FileUtils/IOUtils/CopyUtils) voici un exemple utilisant un BufferedReader pour lire le fichier ligne par ligne:

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);
    }
}

Ou si vous voulez une vitesse brute, je proposerais une variation sur ce que Paul de Vrieze a suggéré (ce qui évite d'utiliser un StringWriter (qui utilise un StringBuffer en interne):

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);
    }
}
 17
Author: DJDaveMark, 2010-05-18 13:05:32

Ceci est une réponse adaptée de org.apache.commons.io.IOUtils code source , pour ceux qui veulent avoir l'implémentation apache mais ne veulent pas toute la bibliothèque.

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();
}
 16
Author: Dreaming in Code, 2015-10-10 04:37:28

Assurez - vous de fermer les flux à la fin si vous utilisez des lecteurs de flux

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();
}

EDIT: Sur JDK 7+, vous pouvez utiliser la construction 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();
    }
}
 16
Author: Thamme Gowda, 2017-02-24 19:28:51

Voici la méthode complète pour convertir InputStream en String sans utiliser de bibliothèque tierce. Utilisez StringBuilder pour un environnement à thread unique sinon utilisez 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();
}
 14
Author: laksys, 2015-12-16 09:20:36

Voici comment le faire en utilisant uniquement le JDK en utilisant des tampons de tableau d'octets. C'est en fait ainsi que fonctionnent toutes les méthodes commons-io IOUtils.copy(). Vous pouvez remplacer byte[] avec char[] si vous copiez à partir d'un Reader au lieu de InputStream.

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);
 13
Author: Matt Shannon, 2014-08-13 04:30:09

Utilisez le java.io.InputStream.transferTo(OutputStream)pris en charge dans Java 9 et le ByteArrayOutputStream.toString (String) {[3] } qui prend le nom du jeu de caractères:

public static String gobble(InputStream in, String charsetName) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    in.transferTo(bos);
    return bos.toString(charsetName);
}
 12
Author: jmehrens, 2017-11-28 14:47:28

Les utilisateurs de Kotlin font simplement:

println(InputStreamReader(is).readText())

Alors que

readText()

Est la méthode d'extension intégrée de la bibliothèque standard Kotlin.

 11
Author: Alex, 2015-02-04 01:12:24

Un autre, pour tous les utilisateurs de 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);
}

Les méthodes utilitaires de org.springframework.util.StreamUtils sont similaires à celles de FileCopyUtils, mais elles laissent le flux ouvert une fois terminé.

 11
Author: James, 2017-07-21 10:24:14

Celui-ci est bien parce que:

  • Main sécurité le jeu de caractères.
  • Vous contrôlez la taille du tampon de lecture.
  • Vous pouvez provisionner la longueur du constructeur et ne peut pas être exactement.
  • est exempt de dépendances de bibliothèque.
  • Est pour Java 7 ou supérieur.

Pour quoi faire?

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();
}
 9
Author: Daniel De León, 2015-04-20 18:17:10

Voici ma solution basée sur Java 8 , qui utilise le new Stream API pour collecter toutes les lignes d'un InputStream:

public static String toString(InputStream inputStream) {
    BufferedReader reader = new BufferedReader(
        new InputStreamReader(inputStream));
    return reader.lines().collect(Collectors.joining(
        System.getProperty("line.separator")));
}
 6
Author: Christian Rädel, 2015-09-02 11:19:27

Le moyen le plus simple dans JDK est avec les extraits de code suivants.

String convertToString(InputStream in){
    String resource = new Scanner(in).useDelimiter("\\Z").next();
    return resource;
}
 6
Author: Raghu K Nair, 2016-08-09 20:18:26

Guava fournit une solution d'autoclosing efficace beaucoup plus courte au cas où le flux d'entrée proviendrait de la ressource classpath (ce qui semble être une tâche populaire):

byte[] bytes = Resources.toByteArray(classLoader.getResource(path));

Ou

String text = Resources.toString(classLoader.getResource(path), StandardCharsets.UTF_8);

Il existe également un concept général de ByteSourceet CharSource qui s'occupent doucement de l'ouverture et de la fermeture du flux.

Ainsi, par exemple, au lieu d'ouvrir explicitement un petit fichier pour lire son contenu:

String content = Files.asCharSource(new File("robots.txt"), StandardCharsets.UTF_8).read();
byte[] data = Files.asByteSource(new File("favicon.ico")).read();

Ou juste

String content = Files.toString(new File("robots.txt"), StandardCharsets.UTF_8);
byte[] data = Files.toByteArray(new File("favicon.ico"));
 4
Author: Vadzim, 2015-07-15 10:50:52

Remarque: Ce n'est probablement pas une bonne idée. Cette méthode utilise la récursivité:

public String read (InputStream is) {
    byte next = is.read();
    return next == -1 ? "" : next + read(is); // Recursive part: reads next byte recursively
}

Veuillez ne pas downvote ceci simplement parce que c'est un mauvais choix à utiliser; c'était surtout créatif:)

 4
Author: HyperNeutrino, 2015-11-17 03:23:02