Created
August 24, 2017 08:21
-
-
Save hendrawd/a2a975e21799294801d2d8d9ba5eed1f to your computer and use it in GitHub Desktop.
Read files with Okio
This file contains hidden or 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.File; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import okhttp3.internal.io.FileSystem; | |
import okio.BufferedSource; | |
import okio.Okio; | |
/** | |
* Utils for I/O operations. | |
*/ | |
public class IoUtils { | |
/** | |
* Reads file and returns a String. | |
* | |
* @param file the file to read | |
* @return the string with file content or null | |
*/ | |
@Nullable | |
public static String tryReadFile(@NonNull final File file) { | |
final BufferedSource source; | |
try { | |
source = Okio.buffer(FileSystem.SYSTEM.source(file)); | |
return source.readUtf8(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
return null; | |
} | |
} | |
/** | |
* Reads InputStream and returns a String. It will close stream after usage. | |
* | |
* @param stream the stream to read | |
* @return the string with file content or null | |
*/ | |
@Nullable | |
public static String tryReadFile(@NonNull final InputStream stream) { | |
final BufferedSource source = Okio.buffer(Okio.source(stream)); | |
try { | |
return source.readUtf8(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
return null; | |
} | |
} | |
/** | |
* Reads file and returns a String. | |
* | |
* @param file the file to read | |
* @return the string content | |
*/ | |
@NonNull | |
public static String readFile(@NonNull final File file) throws IOException { | |
final BufferedSource source = Okio.buffer(FileSystem.SYSTEM.source(file)); | |
return source.readUtf8(); | |
} | |
/** | |
* Reads InputStream and returns a String. It will close stream after usage. | |
* | |
* @param stream the stream to read | |
* @return the string content | |
*/ | |
@NonNull | |
public static String readFile(@NonNull final InputStream stream) throws IOException { | |
final BufferedSource source = Okio.buffer(Okio.source(stream)); | |
return source.readUtf8(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Edited version of https://gist.github.com/ultraon/c6397dfb23de2f260f81e6946ad5adc2 that supports Android API below 19