Created
February 8, 2017 14:03
-
-
Save demixdn/aba112b462ad09be1671801cb63edd41 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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