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) {
// ???
}
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
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.
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:
-
Utiliser
IOUtils.toString
(Apache Utils)String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
-
En utilisant
CharStreams
(goyave)String result = CharStreams.toString(new InputStreamReader( inputStream, Charsets.UTF_8));
-
Utiliser
Scanner
(JDK)Scanner s = new Scanner(inputStream).useDelimiter("\\A"); String result = s.hasNext() ? s.next() : "";
-
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"));
-
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"));
-
En utilisant
InputStreamReader
etStringBuilder
(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();
-
En utilisant
StringWriter
etIOUtils.copy
(Apache Commons)StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, "UTF-8"); return writer.toString();
-
En utilisant
ByteArrayOutputStream
etinputStream.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");
-
En utilisant
BufferedReader
(JDK). Avertissement: Cette solution convertit différents sauts de ligne (comme\n\r
) en propriété systèmeline.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();
-
En utilisant
BufferedInputStream
etByteArrayOutputStream
(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");
-
En utilisant
inputStream.read()
etStringBuilder
(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:
Les solutions 4, 5 et 9 convertissent la ligne différente sauts de à un.
-
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)
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
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)
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();
}
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();
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!)
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;
}
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();
}
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();
}
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.
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.
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.
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"))
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);
}
}
}
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();
}
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
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);
}
}
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();
}
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();
}
}
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();
}
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);
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);
}
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.
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é.
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();
}
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")));
}
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;
}
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"));
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:)