How to convert an InputStream to a String in Java?

11 ways to popular Java issue (with code examples)
15 August 2017   1226

For example, if you have java.io.InputStream object, what should you do to process that object and produce a String?

We've made a research and found 11 ways to solve this task.

  1. With IOUtils.toString (Apache Utils)

    String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
  2. With CharStreams (guava)

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

    Scanner s = new Scanner(inputStream).useDelimiter("\\A");
    String result = s.hasNext() ? s.next() : "";
  4. With Stream Api (Java 8).
    Warning: This solution convert different line breaks (like \r\n) to \n.

    String result = new BufferedReader(new InputStreamReader(inputStream))
      .lines().collect(Collectors.joining("\n"));
  5. With parallel Stream Api (Java 8). 
    Warning: This solution convert different line breaks (like \r\n) to \n.

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

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

    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, "UTF-8");
    return writer.toString();
  8. Using ByteArrayOutputStream and inputStream.read (JDK) (solution with the best performance).

    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. Using BufferedReader (JDK). Warning: This solution convert different line breaks (like \n\r) to line.separator system property (for example, in Windows to "\r\n").

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

    BufferedInputStream bis = new BufferedInputStream(inputStream);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    int result = bis.read();
    while(result != -1) {
        buf.write((byte) result);
        result = bis.read();
    }
    // StandardCharsets.UTF_8.name() > JDK 7
    return buf.toString("UTF-8");
  11. Using inputStream.read() and StringBuilder (JDK). Warning: This solution has problem with Unicode, for example with Russian text (work correctly only with non-Unicode text)

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

 

What is Web3j?

Small review of lightweight Java and Android library for integration with Ethereum clients
15 December 2017   836

What is webj3?

web3j is a lightweight, highly modular, reactive, type safe Java and Android library for working with Smart Contracts and integrating with clients (nodes) on the Ethereum network:

web3j architecture
Web3j Architecture

This allows you to work with the Ethereum blockchain, without the additional overhead of having to write your own integration code for the platform.

According to the developers, these are the features:

  • Complete implementation of Ethereum's JSON-RPC client API over HTTP and IPC
  • Ethereum wallet support
  • Auto-generation of Java smart contract wrappers to create, deploy, transact with and call smart contracts from native Java code (Solidity and Truffle definition formats supported)
  • Reactive-functional API for working with filters
  • Ethereum Name Service (ENS) support
  • Support for Parity's Personal, and Geth's Personal client APIs
  • Support for Infura, so you don't have to run an Ethereum client yourself
  • Comprehensive integration tests demonstrating a number of the above scenarios
  • Command line tools
  • Android compatible
  • Support for JP Morgan's Quorum via web3j-quorum

It has five runtime dependencies:

  • RxJava for its reactive-functional API
  • OKHttp for HTTP connections
  • Jackson Core for fast JSON serialisation/deserialisation
  • Bouncy Castle (Spongy Castle on Android) for crypto
  • Jnr-unixsocket for *nix IPC (not available on Android)

It also uses JavaPoet for generating smart contract wrappers.

Lear more at GitHub.