Skip to content

Instantly share code, notes, and snippets.

@demixdn
Created February 8, 2017 14:03
Show Gist options
  • Save demixdn/aba112b462ad09be1671801cb63edd41 to your computer and use it in GitHub Desktop.
Save demixdn/aba112b462ad09be1671801cb63edd41 to your computer and use it in GitHub Desktop.
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
/**
* @author Aleks Sander
*/
@SuppressWarnings("WeakerAccess")
public final class IOUtils {
private static final String UTF_8 = "UTF-8";
private static final int BUFFER_SIZE = 4096;
private IOUtils() {
//empty
}
@Nullable
public static String getStringFrom(@Nullable InputStream inputStream) throws IOException {
String result = null;
try {
if (inputStream != null) {
result = writeStreamToString(inputStream);
}
} finally {
closeQuietly(inputStream);
}
return result;
}
public static String writeStreamToString(@NonNull InputStream inputStream) throws IOException {
String result;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
result = readStreamAndConvert(inputStream, outputStream);
} finally {
closeQuietly(outputStream);
}
return result;
}
private static String readStreamAndConvert(@NonNull InputStream inputStream, @NonNull ByteArrayOutputStream outputStream) throws IOException {
String result;
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
result = outputStream.toString(UTF_8);
return result;
}
public static void closeQuietly(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch (Exception ex) {
Log.E(ex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment