-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringInputStream.java
53 lines (43 loc) · 1.46 KB
/
StringInputStream.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.tazkiyatech.utils.streams;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import androidx.annotation.NonNull;
/**
* Provides an easy method for reading in the contents of an {@link InputStream}
* and converting it to a {@link String}.
*/
public class StringInputStream implements AutoCloseable {
private static final int BUFFER_SIZE_BYTES = 2048;
@NonNull private final InputStream inputStream;
/**
* Constructor.
*
* @param inputStream the {@link InputStream} instance to read in from.
*/
public StringInputStream(@NonNull InputStream inputStream) {
this.inputStream = inputStream;
}
/**
* Reads in the contents of the {@link InputStream} instance that this class wraps.
*
* @return the value read in from the input stream.
* @throws IOException if an I/O error occurs.
*/
@NonNull
public String read() throws IOException {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(BUFFER_SIZE_BYTES)) {
byte[] buffer = new byte[BUFFER_SIZE_BYTES];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
return outputStream.toString("UTF-8");
}
}
@Override
public void close() throws IOException {
inputStream.close();
}
}