How to convert InputStream to Reader in java?
Asked Answered
T

4

5
  1. reader = new BufferedReader(new InputStreamReader(inputStream))
  2. reader = new InputStreamReader(new BufferedInputStream(inputStream))

which is better? why?

Tombac answered 29/4, 2020 at 11:27 Comment(2)
Does this answer your question? What is the difference between Java's BufferedReader and InputStreamReader classes?Leishaleishmania
@Leishaleishmania that is a different question. though some of the answers of that question is somehow a little helpful.Tombac
T
6

Never create a Reader without providing an encoding. As @CodeScale already mention, first option is better, because it leverages the BufferedReader better and it has convenience methods.

   reader = new BufferedReader(new InputStreamReader(inputStream), StandardCharsets.UTF_8);
Torques answered 29/4, 2020 at 11:45 Comment(0)
M
3

Solution 1 is more efficient.

The BufferedReader can have a larger buffer than InputStreamReader.

Moreover with BufferedReader you have the convenient readline method.

Monecious answered 29/4, 2020 at 11:32 Comment(0)
E
1

Solution 1 is more efficient.

The BufferedReader will read a block of characters from the Reader (typically into a char array). read() method will return data from the internal array.

Eyde answered 29/4, 2020 at 11:36 Comment(1)
Please don't suggest the usage of FileReader you can't provide a Charset. Use Files.newBufferedReader(Paths.get("filename"), StandardCharsets.UTF_8) instead. if you want provide a customer buffer size, you need to go with BufferedReaderTorques
T
1

Benchmark shows the first way (reader = new BufferedReader(new InputStreamReader(inputStream))) is far faster.

But I have no idea why.

benchmark code

package org.apache.commons.io.jmh;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URISyntaxException;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
@Warmup(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS)
@Fork(value = 1, jvmArgs = {"-server"})
public class IOUtilsContentEqualsReadersBenchmark {
    private static final String TEST_PATH_16K_A = "/org/apache/commons/io/abitmorethan16k.txt";

    public static FileInputStream getInputStream() throws URISyntaxException, FileNotFoundException {
        return new FileInputStream(IOUtilsContentEqualsReadersBenchmark.class.getResource(TEST_PATH_16K_A).toURI().getPath());
    }

    @Benchmark
    public static void read1(Blackhole blackhole) throws Exception {
        Reader reader = new BufferedReader(new InputStreamReader(getInputStream()));
        while (true) {
            int res = reader.read();
            blackhole.consume(res);
            if (res == -1) {
                return;
            }
        }
    }

    @Benchmark
    public static void read2(Blackhole blackhole) throws Exception {
        Reader reader = new InputStreamReader(new BufferedInputStream(getInputStream()));
        while (true) {
            int res = reader.read();
            blackhole.consume(res);
            if (res == -1) {
                return;
            }
        }
    }

    @Benchmark
    public static void read3(Blackhole blackhole) throws Exception {
        Reader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(getInputStream())));
        while (true) {
            int res = reader.read();
            blackhole.consume(res);
            if (res == -1) {
                return;
            }
        }
    }
}

benchmark result

[INFO] --- exec-maven-plugin:3.0.0:exec (benchmark) @ commons-io ---
# JMH version: 1.27
# VM version: JDK 1.8.0_275, OpenJDK 64-Bit Server VM, 25.275-b01
# VM invoker: C:\jdk8u275-b01\jre\bin\java.exe
# VM options: -server
# JMH blackhole mode: full blackhole + dont-inline hint
# Warmup: 5 iterations, 10 s each
# Measurement: 5 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Average time, time/op
# Benchmark: org.apache.commons.io.jmh.IOUtilsContentEqualsReadersBenchmark.read1

# Run progress: 0.00% complete, ETA 00:05:00
# Fork: 1 of 1
# Warmup Iteration   1: 141144.322 ns/op
# Warmup Iteration   2: 126969.546 ns/op
# Warmup Iteration   3: 117894.788 ns/op
# Warmup Iteration   4: 118555.020 ns/op
# Warmup Iteration   5: 117377.183 ns/op
Iteration   1: 118137.872 ns/op
Iteration   2: 117869.504 ns/op
Iteration   3: 117894.961 ns/op
Iteration   4: 118090.279 ns/op
Iteration   5: 117234.480 ns/op


Result "org.apache.commons.io.jmh.IOUtilsContentEqualsReadersBenchmark.read1":
  117845.419 ��(99.9%) 1390.724 ns/op [Average]
  (min, avg, max) = (117234.480, 117845.419, 118137.872), stdev = 361.167
  CI (99.9%): [116454.695, 119236.143] (assumes normal distribution)


# JMH version: 1.27
# VM version: JDK 1.8.0_275, OpenJDK 64-Bit Server VM, 25.275-b01
# VM invoker: C:\jdk8u275-b01\jre\bin\java.exe
# VM options: -server
# JMH blackhole mode: full blackhole + dont-inline hint
# Warmup: 5 iterations, 10 s each
# Measurement: 5 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Average time, time/op
# Benchmark: org.apache.commons.io.jmh.IOUtilsContentEqualsReadersBenchmark.read2

# Run progress: 33.33% complete, ETA 00:03:20
# Fork: 1 of 1
# Warmup Iteration   1: 287001.406 ns/op
# Warmup Iteration   2: 269609.908 ns/op
# Warmup Iteration   3: 268606.597 ns/op
# Warmup Iteration   4: 259708.116 ns/op
# Warmup Iteration   5: 256359.254 ns/op
Iteration   1: 256837.341 ns/op
Iteration   2: 257773.909 ns/op
Iteration   3: 256669.369 ns/op
Iteration   4: 258031.384 ns/op
Iteration   5: 258269.111 ns/op


Result "org.apache.commons.io.jmh.IOUtilsContentEqualsReadersBenchmark.read2":
  257516.223 ��(99.9%) 2774.519 ns/op [Average]
  (min, avg, max) = (256669.369, 257516.223, 258269.111), stdev = 720.534
  CI (99.9%): [254741.704, 260290.742] (assumes normal distribution)


# JMH version: 1.27
# VM version: JDK 1.8.0_275, OpenJDK 64-Bit Server VM, 25.275-b01
# VM invoker: C:\jdk8u275-b01\jre\bin\java.exe
# VM options: -server
# JMH blackhole mode: full blackhole + dont-inline hint
# Warmup: 5 iterations, 10 s each
# Measurement: 5 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Average time, time/op
# Benchmark: org.apache.commons.io.jmh.IOUtilsContentEqualsReadersBenchmark.read3

# Run progress: 66.67% complete, ETA 00:01:40
# Fork: 1 of 1
# Warmup Iteration   1: 146614.866 ns/op
# Warmup Iteration   2: 131029.887 ns/op
# Warmup Iteration   3: 120476.530 ns/op
# Warmup Iteration   4: 121140.296 ns/op
# Warmup Iteration   5: 119992.159 ns/op
Iteration   1: 120754.048 ns/op
Iteration   2: 120544.731 ns/op
Iteration   3: 120556.412 ns/op
Iteration   4: 120781.589 ns/op
Iteration   5: 120338.529 ns/op


Result "org.apache.commons.io.jmh.IOUtilsContentEqualsReadersBenchmark.read3":
  120595.062 ��(99.9%) 693.931 ns/op [Average]
  (min, avg, max) = (120338.529, 120595.062, 120781.589), stdev = 180.212
  CI (99.9%): [119901.131, 121288.993] (assumes normal distribution)


# Run complete. Total time: 00:05:01

REMEMBER: The numbers below are just data. To gain reusable insights, you need to follow up on
why the numbers are the way they are. Use profilers (see -prof, -lprof), design factorial
experiments, perform baseline and negative tests that provide experimental control, make sure
the benchmarking environment is safe on JVM/OS/HW level, ask for reviews from the domain experts.
Do not assume the numbers tell you what you want them to tell.

Benchmark                                   Mode  Cnt       Score      Error  Units
IOUtilsContentEqualsReadersBenchmark.read1  avgt    5  117845.419 �� 1390.724  ns/op
IOUtilsContentEqualsReadersBenchmark.read2  avgt    5  257516.223 �� 2774.519  ns/op
IOUtilsContentEqualsReadersBenchmark.read3  avgt    5  120595.062 ��  693.931  ns/op

Benchmark result is saved to target/jmh-result.org.apache.json
Tombac answered 19/2, 2021 at 4:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.