Come faccio a leggere / convertire un InputStream in una stringa in Java?
-
08-07-2019 - |
Domanda
Se hai un oggetto java.io.InputStream
, come dovresti elaborare quell'oggetto e produrre un String
?
Supponiamo di avere un InputStream
che contiene dati di testo e che voglio convertirlo in un String
, quindi ad esempio posso scriverlo in un file di registro.
Qual è il modo più semplice per prendere InputStream
e convertirlo in String
?
public String convertStreamToString(InputStream is) {
// ???
}
Soluzione
Un buon modo per farlo è usare Apache commons IOUtils
per copiare < code> InputStream in un StringWriter
... qualcosa come
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
o persino
// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding);
In alternativa, puoi usare ByteArrayOutputStream
se non vuoi mescolare i tuoi stream e scrittori
Altri suggerimenti
Ecco un modo utilizzando solo la libreria Java standard (nota che lo stream non è chiuso, il chilometraggio può variare).
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
Ho imparato questo trucco da " Stupid Scanner tricks " ; articolo. Il motivo per cui funziona è perché Scanner ripete token nello stream, e in questo caso separiamo i token usando " inizio del limite di input " (\ A), dandoci così un solo token per l'intero contenuto dello stream.
Nota, se devi essere specifico sulla codifica del flusso di input, puoi fornire il secondo argomento al costruttore Scanner
che indica quale set di caratteri usare (es. " UTF-8 " ;).
La punta del cappello va anche a Jacob , che una volta mi ha indicato l'articolo detto.
Riassumi altre risposte Ho trovato 11 modi principali per farlo (vedi sotto). E ho scritto alcuni test delle prestazioni (vedere i risultati di seguito):
Modi per convertire un InputStream in una stringa:
-
Uso di
IOUtils.toString
(Apache Utils)String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
-
Uso di
CharStreams
(Guava)String result = CharStreams.toString(new InputStreamReader( inputStream, Charsets.UTF_8));
-
Uso di
Scanner
(JDK)Scanner s = new Scanner(inputStream).useDelimiter("\\A"); String result = s.hasNext() ? s.next() : "";
-
Uso di API Stream (Java 8). Avviso : questa soluzione converte diverse interruzioni di riga (come
\ r \ n
) in\ n
.String result = new BufferedReader(new InputStreamReader(inputStream)) .lines().collect(Collectors.joining("\n"));
-
Uso di API flusso parallelo (Java 8). Avviso : questa soluzione converte diverse interruzioni di riga (come
\ r \ n
) in\ n
.String result = new BufferedReader(new InputStreamReader(inputStream)).lines() .parallel().collect(Collectors.joining("\n"));
-
Uso di
InputStreamReader
eStringBuilder
(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();
-
Uso di
StringWriter
eIOUtils.copy
(Apache Commons)StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, "UTF-8"); return writer.toString();
-
Uso di
ByteArrayOutputStream
einputStream.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");
-
Uso di
BufferedReader
(JDK). Avviso: questa soluzione converte diverse interruzioni di riga (come\ n \ r
) inline.separator
proprietà di sistema (ad esempio, in Windows in " ; \ r \ n ").String newLine = System.getProperty("line.separator"); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder result = new StringBuilder(); boolean flag = false; for (String line; (line = reader.readLine()) != null; ) { result.append(flag? newLine: "").append(line); flag = true; } return result.toString();
-
Uso di
BufferedInputStream
eByteArrayOutputStream
(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");
-
Uso di
inputStream.read ()
eStringBuilder
(JDK). Avviso : questa soluzione presenta problemi con Unicode, ad esempio con testo russo (funziona correttamente solo con testo non Unicode)int ch; StringBuilder sb = new StringBuilder(); while((ch = inputStream.read()) != -1) sb.append((char)ch); reset(); return sb.toString();
Attenzione :
-
Le soluzioni 4, 5 e 9 convertono diverse interruzioni di linea in una.
-
La soluzione 11 non può funzionare correttamente con il testo Unicode
Test delle prestazioni
Test delle prestazioni per String
(lunghezza = 175), url in github (mode = Tempo medio, sistema = Linux, il punteggio 1.343 è il migliore):
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
Test delle prestazioni per la grande String
(lunghezza = 50100), url in github (mode = Tempo medio, sistema = Linux, il punteggio 200.715 è il migliore):
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
Grafici (test delle prestazioni in base alla lunghezza del flusso di input nel sistema Windows 7)
Test delle prestazioni (tempo medio) in base alla lunghezza del flusso di input nel sistema 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 consente:
String myString = IOUtils.toString(myInputStream, "UTF-8");
Ovviamente, potresti scegliere altre codifiche di caratteri oltre a UTF-8.
Vedi anche: ( documentazione )
Tenendo conto del file dell'account, si dovrebbe prima ottenere un'istanza java.io.Reader
. Questo può quindi essere letto e aggiunto a un StringBuilder
(non abbiamo bisogno di StringBuffer
se non accediamo ad esso in più thread e StringBuilder
è più veloce). Il trucco qui è che lavoriamo in blocchi e come tali non abbiamo bisogno di altri flussi di buffering. La dimensione del blocco è parametrizzata per l'ottimizzazione delle prestazioni di runtime.
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();
}
Usa:
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();
Se si utilizza Google-Collections / Guava è possibile effettuare le seguenti operazioni:
InputStream stream = ...
String content = CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8));
Closeables.closeQuietly(stream);
Nota che il secondo parametro (es. Charsets.UTF_8) per InputStreamReader
non è necessario, ma è generalmente una buona idea specificare la codifica se la conosci (cosa che dovresti!)
Questa è la mia pura soluzione Java e Android e funziona bene ...
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;
}
Ecco la soluzione più elegante, pura di Java (senza libreria) che ho trovato dopo un po 'di sperimentazione:
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();
}
Usa:
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();
}
Per completezza ecco la soluzione Java 9 :
public static String toString(InputStream input) throws IOException {
return new String(input.readAllBytes(), StandardCharsets.UTF_8);
}
Il readAllBytes
è attualmente nella base di codice principale di JDK 9, quindi è probabile che appaia nella versione. Puoi provarlo adesso usando le build snapshot JDK 9 .
Ho fatto un benchmark su 14 risposte distinte qui (scusate per non aver fornito crediti ma ci sono troppi duplicati).
Il risultato è molto sorprendente. Si scopre che Apache IOUtils è il più lento e ByteArrayOutputStream
è la soluzione più veloce:
Quindi, prima di tutto, ecco il metodo migliore:
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);
}
}
Risultati benchmark, di 20 MB di byte casuali in 20 cicli
Tempo in millisecondi
- ByteArrayOutputStreamTest: 194
- NioStream: 198
- Java9ISTransferTo: 201
- Java9ISReadAllBytes: 205
- BufferedInputStreamVsByteArrayOutputStream: 314
- ApacheStringWriter2: 574
- GuavaCharStreams: 589
- ScannerReaderNoNextTest: 614
- ScannerReader: 633
- ApacheStringWriter: 1544
- StreamApi: errore
- ParallelStreamApi: errore
- BufferReaderTest: errore
- InputStreamAndStringBuilder: errore
Codice sorgente benchmark
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);
}
}
}
Vorrei usare alcuni trucchi 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.
}
}
Sostanzialmente uguale ad alcune altre risposte tranne quelle più sintetiche.
Ho eseguito alcuni test di temporizzazione perché il tempo è importante, sempre.
Ho tentato di ottenere la risposta in una stringa 3 in diversi modi. (mostrato sotto)
Ho omesso di provare / catturare i blocchi per la leggibilità del bene.
Per dare un contesto, questo è il codice precedente per tutti e 3 gli approcci:
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();
Quindi, dopo aver eseguito 500 test su ciascun approccio con gli stessi dati di richiesta / risposta, ecco i numeri. Ancora una volta, questi sono i miei risultati e i tuoi risultati potrebbero non essere esattamente gli stessi, ma ho scritto questo per dare qualche indicazione agli altri sulle differenze di efficienza di questi approcci.
Classifiche:
Approccio n. 1
Approccio n. 3 - 2,6% più lento rispetto al n. 1
Approccio n. 2 - 4,3% più lento rispetto al n. 1
Ognuno di questi approcci è una soluzione appropriata per afferrare una risposta e creare una stringa da essa.
Soluzione Java pura che utilizza Stream s, funziona da 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()));
}
}
Come menzionato da Christoffer Hammarström sotto altra risposta è più sicuro specificare esplicitamente Charset . Cioè Il costruttore InputStreamReader può essere modificato come segue:
new InputStreamReader(is, Charset.forName("UTF-8"))
Ecco la risposta di sampath più o meno, ripulita un po 'e rappresentata come una funzione:
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();
}
Se ti sentissi avventuroso, potresti mescolare Scala e Java e finire con questo:
scala.io.Source.fromInputStream(is).mkString("")
La combinazione di codice e librerie Java e Scala ha i suoi vantaggi.
Vedi la descrizione completa qui: Modo idiomatico per convertire un InputStream in una stringa in Scala
Se non puoi usare Commons IO (FileUtils / IOUtils / CopyUtils), ecco un esempio usando un BufferedReader per leggere il file riga per riga:
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);
}
}
O se vuoi la velocità pura ti proporrei una variazione su ciò che Paul de Vrieze ha suggerito (che evita di usare StringWriter (che utilizza uno StringBuffer internamente):
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);
}
}
Questa è una risposta adattata da org.apache.commons.io.IOUtils
codice sorgente , per coloro che vogliono avere l'implementazione di apache ma non vogliono l'intera libreria.
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();
}
Assicurati di chiudere i flussi alla fine se usi Stream Reader
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: su JDK 7+, puoi usare il costrutto 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();
}
}
Ecco il metodo completo per convertire InputStream
in String
senza usare alcuna libreria di terze parti. Usa StringBuilder
per un ambiente a thread singolo, altrimenti usa 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();
}
Ecco come farlo usando solo JDK usando i buffer di array di byte. Questo è in realtà il modo in cui funzionano tutti i metodi IOUtils.copy ()
di commons-io. Puoi sostituire byte []
con char []
se stai copiando da un Reader
invece di un 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);
Un altro, per tutti gli utenti 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);
}
I metodi di utilità in org.springframework.util.StreamUtils
sono simili a quelli in FileCopyUtils
, ma al termine lasciano lo stream aperto.
Gli utenti di Kotlin fanno semplicemente:
println(InputStreamReader(is).readText())
considerando
readText()
è il metodo di estensione incorporato della libreria standard di Kotlin.
Utilizza java.io.InputStream.transferTo (OutputStream) supportato in Java 9 e ByteArrayOutputStream.toString (String) che prende il nome del set di caratteri:
public static String gobble(InputStream in, String charsetName) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
in.transferTo(bos);
return bos.toString(charsetName);
}
Questo è carino perché:
- Gestisce in sicurezza Charset.
- Controlli la dimensione del buffer di lettura.
- Puoi eseguire il provisioning della lunghezza del builder e non deve essere un valore esatto.
- È libero dalle dipendenze delle biblioteche.
- È per Java 7 o versioni successive.
Come si fa?
public static String convertStreamToString(InputStream is) throws IOException {
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));
}
return sb.toString();
}
Per JDK 9
public static String inputStreamString(InputStream inputStream) throws IOException {
try (inputStream) {
return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
}
}
Il modo più semplice in JDK è con i seguenti frammenti di codice.
String convertToString(InputStream in){
String resource = new Scanner(in).useDelimiter("\\Z").next();
return resource;
}
Ecco la mia soluzione Java 8 , che utilizza la nuova API Stream per raccogliere tutte le righe da 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")));
}
inputStream.getText()
In termini di riduci
e concat
può essere espresso in Java 8 come:
String fromFile = new BufferedReader(new
InputStreamReader(inputStream)).lines().reduce(String::concat).get();