Bir InputStream'i Java'da bir Dizgeye nas─▒l okurum / d├Ân├╝┼čt├╝r├╝r├╝m?


Al─▒nan cevaba git


Bir java.io.InputStream nesneniz varsa, bu nesneyi nas─▒l i┼člemeli ve bir ├╝r├╝n ├╝retmelisiniz String ?


Diyelim InputStream ki metin verileri i├žeren bir dosyam var ve onu a'ya d├Ân├╝┼čt├╝rmek istiyorum String , ├Ârne─čin bunu bir g├╝nl├╝k dosyas─▒na yazabilirim.

Bunu al─▒p InputStream d├Ân├╝┼čt├╝rmenin en kolay yolu nedir String ?

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

3816









Cevap say─▒s─▒n─▒ say: 30






Bunu yapmak i├žin g├╝zel bir yolu kullan─▒yor Apache commons IOUtils kopyalamak i├žin InputStream bir i├žine StringWriter gibi ... ┼čey

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

ya da

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

Alternatif olarak, ByteArrayOutputStream Ak─▒┼člar─▒n─▒z─▒ ve Yazarlar─▒n─▒z─▒ kar─▒┼čt─▒rmak istemiyorsan─▒z kullanabilirsiniz.


2405







Yaln─▒zca standart Java k├╝t├╝phanesini kullanman─▒n bir yolu var (ak─▒┼č─▒n kapal─▒ olmad─▒─č─▒n─▒, kilometrenizin de─či┼čebilece─čini unutmay─▒n).

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

Bu numaray─▒ "Aptal Taray─▒c─▒ P├╝f Noktalar─▒" makalesinden ├Â─črendim . ├çal─▒┼čmas─▒n─▒n nedeni, Taray─▒c─▒ ak─▒┼č─▒ndaki belirte├žler ├╝zerinde yineleniyor ve bu durumda belirte├žleri "giri┼č s─▒n─▒r─▒n─▒n ba┼člang─▒c─▒" (\ A) kullanarak ay─▒r─▒yoruz, b├Âylece bize ak─▒┼č─▒n t├╝m i├žeri─či i├žin yaln─▒zca bir simge veriyoruz.

Girdi ak─▒┼č─▒n─▒n kodlamas─▒ konusunda spesifik olman─▒z gerekiyorsa Scanner , hangi karakterin kullan─▒laca─č─▒n─▒ belirten yap─▒c─▒ya ikinci arg├╝man─▒ sa─člayabilirsiniz (├Ârne─čin, "UTF-8").

┼×apka ipucu da bir keresinde beni s├Âz konusu makaleye y├Ânlendiren Yakup'a gider .


2266







Di─čer cevaplar─▒ ├Âzetle Bunu yapman─▒n 11 ana yolunu buldum (a┼ča─č─▒ya bak─▒n─▒z). Ve baz─▒ performans testleri yazd─▒m (a┼ča─č─▒daki sonu├žlara bak─▒n):

InputStream'i Dizeye D├Ân├╝┼čt├╝rmenin Yollar─▒:

  1. Kullanma IOUtils.toString (Apache Utils)

     String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
     
  2. Kullanma CharStreams (Guava)

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

     Scanner s = new Scanner(inputStream).useDelimiter("\\A");
    String result = s.hasNext() ? s.next() : "";
     
  4. Stream API'yi kullanma (Java 8). Uyar─▒ : Bu ├ž├Âz├╝m, farkl─▒ sat─▒r sonlar─▒n─▒ (benzeri \r\n ) 'e d├Ân├╝┼čt├╝r├╝r \n .

     String result = new BufferedReader(new InputStreamReader(inputStream))
      .lines().collect(Collectors.joining("\n"));
     
  5. Paralel Ak─▒┼č API'sini kullanma (Java 8). Uyar─▒ : Bu ├ž├Âz├╝m, farkl─▒ sat─▒r sonlar─▒n─▒ (benzeri \r\n ) 'e d├Ân├╝┼čt├╝r├╝r \n .

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

     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. Kullanma StringWriter ve IOUtils.copy (Apache Commons)

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

     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. BufferedReader (JDK) kullanarak . Uyar─▒: Bu ├ž├Âz├╝m farkl─▒ sat─▒r sonlar─▒n─▒ (like \n\r ) line.separator sistem ├Âzelli─čine (├Ârne─čin, Windows'ta "\ r \ n") d├Ân├╝┼čt├╝r├╝r.

     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();
     
  10. BufferedInputStream Ve ByteArrayOutputStream (JDK) kullanarak

     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. inputStream.read() Ve StringBuilder (JDK) kullanarak . Uyar─▒ : Bu ├ž├Âz├╝m, ├Ârne─čin Rus├ža metinle birlikte Unicode ile ilgili sorunlara sahiptir (yaln─▒zca Unicode olmayan metinlerle d├╝zg├╝n ├žal─▒┼č─▒r)

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

Uyar─▒ :

  1. 4, 5 ve 9 numaral─▒ ├ž├Âz├╝mler farkl─▒ sat─▒r sonlar─▒n─▒ bire d├Ân├╝┼čt├╝r├╝yor.

  2. 11. ├ç├Âz├╝m Unicode metinle d├╝zg├╝n ├žal─▒┼čam─▒yor

Performans testleri

K├╝├ž├╝k i├žin performans testleri String (uzunluk = 175), github'da url (mod = Ortalama S├╝re, sistem = Linux, skor 1,343 en iyisidir):

               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
 

Big i├žin performans testleri String (uzunluk = 50100), url github (mod = Ortalama S├╝re, sistem = Linux, 200.715 iyisi skor):

                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
 

Grafikler (Windows 7 sisteminde Giri┼č Ak─▒┼č─▒ uzunlu─čuna ba─čl─▒ olarak performans testleri)

g├Âr├╝nt├╝ tan─▒m─▒n─▒ buraya girin

Windows 7 sistemindeki Giri┼č Ak─▒┼č─▒ uzunlu─čuna ba─čl─▒ olarak performans testi (Ortalama S├╝re):

  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
 

2210







Apache Commons ┼čunlar─▒ sa─člar:

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

Tabii ki, UTF-8 d─▒┼č─▒nda ba┼čka karakter kodlamalar─▒ se├žebilirsiniz.

Ayr─▒ca bak─▒n─▒z: ( belgeler )


835







Bir hesap dosyas─▒ dikkate al─▒narak ilk ├Ânce bir java.io.Reader ├Ârnek al─▒nmal─▒d─▒r . Bu daha sonra okunabilir ve eklenebilir StringBuilder ( StringBuffer birden fazla i┼č par├žac─▒─č─▒na eri┼čemedi─čimizde ihtiyac─▒m─▒z yoktur ve StringBuilder daha h─▒zl─▒d─▒r). Buradaki hile, bloklar halinde ├žal─▒┼čmam─▒z ve bu nedenle ba┼čka tamponlama ak─▒┼člar─▒na ihtiya├ž duymamas─▒d─▒r. Blok boyutu, ├žal─▒┼čma zaman─▒ performans optimizasyonu i├žin parametrelendirildi.

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

290







kullan─▒n:

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

245







Google-Collections / Guava kullan─▒yorsan─▒z, a┼ča─č─▒dakileri yapabilirsiniz:

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

Bunun i├žin ikinci parametrenin (├Ârne─čin, Charsets.UTF_8) InputStreamReader gerekli olmad─▒─č─▒na dikkat edin, ancak e─čer biliyorsan─▒z kodlama belirtmeniz genellikle iyi bir fikirdir (hangisi!)


172







Bu, Android ve di─čer JVM'ler i├žin m├╝kemmel olan en saf Java ├ž├Âz├╝m├╝d├╝r.

Bu ├ž├Âz├╝m ┼ča┼č─▒rt─▒c─▒ derecede iyi ├žal─▒┼č─▒yor ... basit, h─▒zl─▒ ve k├╝├ž├╝k ve b├╝y├╝k ak─▒┼člarda ayn─▒ ┼čekilde ├žal─▒┼č─▒yor !! (yukar─▒daki k─▒yaslamaya bak─▒n─▒z .. No. 8 )

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

121







─░┼čte baz─▒ deneylerden sonra elde etti─čim en zarif, saf Java (k├╝t├╝phane yok) ├ž├Âz├╝m├╝:

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

63







B├╝t├╝nl├╝─č├╝ i├žin burada Java 9 ├ž├Âz├╝m├╝:

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

readAllBytes B├╝y├╝k olas─▒l─▒kla s├╝r├╝mde g├Âr├╝nmesini, b├Âylece JDK 9 ana kod temeli ┼ču anda. JDK 9 anl─▒k g├Âr├╝nt├╝ olu┼čturmalar─▒n─▒ kullanarak hemen deneyebilirsiniz .


63







kullan─▒n:

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

63







Burada 14 ayr─▒ cevap ├╝zerinde bir de─čerlendirme yapt─▒m (kredi sa─člamad─▒─č─▒m i├žin ├╝zg├╝n├╝m ama ├žok fazla kopya var).

Sonu├ž ├žok ┼ča┼č─▒rt─▒c─▒. Apache IOUtils'in en yava┼č ve ByteArrayOutputStream en h─▒zl─▒ ├ž├Âz├╝m oldu─ču ortaya ├ž─▒kt─▒ :

Yani burada ilk olarak en iyi y├Ântem:

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

        return result.toString(UTF_8);
    }
}
 

20 d├Âng├╝de 20 MB rastgele bayt─▒n K─▒yaslama sonu├žlar─▒

Milisaniye cinsinden s├╝re

  • ByteArrayOutputStreamTest: 194
  • NioStream: 198
  • Java9ISTransferTo: 201
  • Java9ISReadAllBytes: 205
  • BufferedInputStreamVsByteArrayOutputStream: 314
  • ApacheStringWriter2: 574
  • GuavaCharStreams: 589
  • Taray─▒c─▒ReaderNoNextTest: 614
  • Taray─▒c─▒ Okuyucu: 633
  • ApacheStringWriter: 1544
  • StreamApi: Hata
  • ParallelStreamApi: Hata
  • BufferReaderTest: Hata
  • InputStreamAndStringBuilder: Hata

Kar┼č─▒la┼čt─▒rma kaynak kodu

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

}
 

54







Baz─▒ Java 8 p├╝f noktalar─▒ kullan─▒rd─▒m.

 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.
    }
}
 

Temelde daha ├Âzl├╝ hari├ž baz─▒ di─čer cevaplarla ayn─▒.


41







Baz─▒ zamanlama testleri yapt─▒m ├ž├╝nk├╝ zaman her zaman ├Ânemli.

Bir String 3 cevab─▒n─▒ cevaplamaya ├žal─▒┼čt─▒m. (a┼ča─č─▒da g├Âsterilmi┼čtir)
Okunabilirlik i├žin denemek / yakalamak bloklar─▒ b─▒rakt─▒.

Ba─člam vermek gerekirse, bu 3 yakla┼č─▒m─▒n t├╝m├╝ i├žin bir ├Ânceki koddur:

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

B├Âylece, her bir yakla┼č─▒m i├žin ayn─▒ istek / yan─▒t verisi ile 500 test yapt─▒ktan sonra, i┼čte say─▒lar. Bir kez daha, bunlar benim bulgular─▒m ve bulgular─▒n─▒z tam olarak ayn─▒ olmayabilir, ancak bunu ba┼čkalar─▒na bu yakla┼č─▒mlar─▒n verimlilik farkl─▒l─▒klar─▒na dair bir g├Âsterge vermek i├žin yazd─▒m.

Ranks:
Yakla┼č─▒m # 1
Yakla┼č─▒m # 3 - # 1'den% 2.6 yava┼čt─▒r # 1
Yakla┼č─▒m # 2 - 4.3 #'den 1 yava┼čt─▒r

Bu yakla┼č─▒mlardan herhangi biri bir yan─▒t almak ve bir Dize olu┼čturmak i├žin uygun bir ├ž├Âz├╝md├╝r.


34







Stream s kullanarak saf Java ├ž├Âz├╝m├╝ , Java 8'den beri ├žal─▒┼č─▒yor.

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

Christoffer Hammarstr├Âm taraf─▒ndan di─čer cevab─▒n alt─▒nda belirtildi─či gibi, Charset'in a├ž─▒k├ža belirtilmesi daha g├╝venlidir . Yani InputStreamReader yap─▒c─▒s─▒ a┼ča─č─▒daki gibi de─či┼čtirilebilir:

 new InputStreamReader(is, Charset.forName("UTF-8"))
 

32







─░┼čte az ya da ├žok sampath'─▒n cevab─▒, biraz temizlendi ve bir i┼člev olarak g├Âsterildi:

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

26


2012-03-30





Kendini macerac─▒ hissediyorsan, Scala ve Java'y─▒ kar─▒┼čt─▒r─▒p bununla sonu├žlanabilir:

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

Java ve Scala kodunu ve kitapl─▒klar─▒n─▒ kar─▒┼čt─▒rman─▒n yararlar─▒ vard─▒r.

Buraya tam a├ž─▒klamas─▒na bak─▒n: Bir InputStream'i Scala'da bir Dize'ye d├Ân├╝┼čt├╝rmenin deyimsel yolu


24


2012-03-07





Commons IO (FileUtils / IOUtils / CopyUtils) kullanam─▒yorsan─▒z, i┼čte sat─▒r sat─▒r dosya okumak i├žin bir BufferedReader kullanan bir ├Ârnek:

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

Veya ham h─▒z istiyorsan─▒z, Paul de Vrieze'nin ├Ânerdi─či ┼čeyde bir de─či┼čiklik ├Ânerebilirim (bir StringWriter kullanmaktan ka├ž─▒n─▒r (dahili olarak bir StringBuffer kullan─▒r):

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

21







Bu, apache uygulamas─▒na sahip olmak, ancak k├╝t├╝phanenin tamam─▒n─▒ istememek isteyenler i├žin org.apache.commons.io.IOUtils kaynak kodundan uyarlanm─▒┼č bir cevapt─▒r .

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

18







Ak─▒┼č Okuyucular kullan─▒yorsan─▒z, ak─▒┼člar─▒ sonda kapatt─▒─č─▒n─▒zdan emin olun.

 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: JDK 7+ 'da, try-with yap─▒s─▒n─▒ kullanabilirsiniz.

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

17







─░┼čte d├Ân├╝┼čt├╝rmek i├žin komple bir y├Ântemdir InputStream i├žine String herhangi bir ├╝├ž├╝nc├╝ taraf kitapl─▒─č─▒ kullanmadan. StringBuilder Tek di┼čli ortam i├žin kullan─▒n , aksi takdirde kullan─▒n 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();
}
 

15







─░┼čte byte dizi tamponlar─▒n─▒ kullanarak sadece JDK kullanarak nas─▒l yapaca─č─▒n─▒z. Bu asl─▒nda ortak kullan─▒m IOUtils.copy() y├Ântemlerinin hepsinin i┼čleyi┼čidir. Bir yerine kopyal─▒yorsan─▒z, byte[] ile de─či┼čtirebilirsiniz . char[] Reader 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);
 

14







Bu g├╝zel ├ž├╝nk├╝:

  • Charset'i g├╝venle kullan─▒r.
  • Okuma arabelle─či boyutunu kontrol edersiniz.
  • Yap─▒mc─▒n─▒n uzunlu─čunu sa─člayabilirsiniz ve bunun kesin bir de─čer olmas─▒ gerekmez.
  • K├╝t├╝phane ba─č─▒ml─▒l─▒klar─▒ndan muaft─▒r.
  • Java 7 veya ├╝st├╝ i├žindir.

Nas─▒l yap─▒l─▒r?

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

JDK 9 i├žin

 public static String inputStreamString(InputStream inputStream) throws IOException {
    try (inputStream) {
        return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
    }
}
 

14







Kotlin kullan─▒c─▒lar─▒ basit├že:

 println(InputStreamReader(is).readText())
 

buna kar┼č─▒l─▒k

 readText()
 

Kotlin standart k├╝t├╝phanesinin yerle┼čik uzatma y├Ântemidir.


13


2015-02-04





T├╝m Spring kullan─▒c─▒lar─▒ i├žin bir tane daha:

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

Yard─▒mc─▒ uygulama y├Ântemleri i├žindekilere org.springframework.util.StreamUtils benzer FileCopyUtils , ancak bitti─činde ak─▒┼č─▒ a├ž─▒k b─▒rak─▒r.


13







Kullan java.io.InputStream.transferTo (OutputStream) Java 9'da desteklenen ve ByteArrayOutputStream.toString (String) charset ad─▒n─▒ al─▒r:

 public static String gobble(InputStream in, String charsetName) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    in.transferTo(bos);
    return bos.toString(charsetName);
}
 

12







JDK'daki en kolay yol a┼ča─č─▒daki kod par├žac─▒klar─▒d─▒r.

 String convertToString(InputStream in){
    String resource = new Scanner(in).useDelimiter("\\Z").next();
    return resource;
}
 

7







─░┼čte bir sat─▒rdaki t├╝m sat─▒rlar─▒ toplamak i├žin yeni Stream API'yi kullanan Java 8 tabanl─▒ ├ž├Âz├╝m├╝m : 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







Groovy'de

 inputStream.getText()
 

5







A├ž─▒s─▒ndan reduce ve concat Java 8'deki gibi ifade edilebilir:

 String fromFile = new BufferedReader(new   
InputStreamReader(inputStream)).lines().reduce(String::concat).get();
 

5



─░lgili yay─▒nlar


Bir tam say─▒y─▒ JavaScript'te ikiliye nas─▒l d├Ân├╝┼čt├╝r├╝r├╝m?

C dizesinde bir dizi dizini nas─▒l olu┼čturabilirim?

Java'da int'den Long'a nas─▒l d├Ân├╝┼čt├╝rebilirim?

C++ 'ta ├žiftini dizeye nas─▒l d├Ân├╝┼čt├╝rebilirim?

Bir Tamsay─▒ Excel VBA'da Bir Dizeye Nas─▒l D├Ân├╝┼čt├╝r├╝r├╝m?

Bir dizi nesnesini PowerShell'deki bir dizeye nas─▒l d├Ân├╝┼čt├╝rebilirim?

Bir aral─▒─č─▒ postgres ile birka├ž saate nas─▒l d├Ân├╝┼čt├╝rebilirim?

Stringstream'den C++ 'a dizgiye nas─▒l d├Ânebilirim?

Ge├žerli tarih java'da dize d├Ân├╝┼čt├╝rmek nas─▒l?

Bir tamsay─▒y─▒ PostgreSQL sorgusunun bir par├žas─▒ olarak dizgeye nas─▒l d├Ân├╝┼čt├╝rebilirim?

Etiketle ilgili di─čer sorular [java]


Windows'ta bir ba─člant─▒ noktas─▒nda hangi i┼člemin dinlendi─čini nas─▒l ├Â─črenebilirsiniz?

git projesindeki herhangi bir 'bin' dizinini yok sayarak

Python'da 'ben' kelimesinin amac─▒ nedir?

Git'te tek bir ┼čubeyi nas─▒l klonlar─▒m?

React / React Native'da constructor vs getInitialState kullanma aras─▒ndaki fark nedir?

G├Âr├╝nt├╝ de─či┼čtirildikten sonra liman i┼č├žisi konteyneri nas─▒l y├╝kseltilir

Java Hashmap: Anahtardan de─čer nas─▒l al─▒n─▒r?

Git takma adlar─▒n─▒ listele

MySQL'de --secure-file-priv ile nas─▒l ba┼ča ├ž─▒kmal─▒y─▒m?

GitHub'taki bir havuzu nas─▒l yeniden adland─▒rabilirim?