Created
May 25, 2017 21:37
-
-
Save ultraon/c6397dfb23de2f260f81e6946ad5adc2 to your computer and use it in GitHub Desktop.
Utils for I/O operations
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 okhttp3.internal.io.FileSystem; | |
import okio.BufferedSource; | |
import okio.Okio; | |
import java.io.File; | |
import java.io.IOException; | |
import java.io.InputStream; | |
/** | |
* 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) { | |
try (final BufferedSource source = Okio.buffer(FileSystem.SYSTEM.source(file))) { | |
return source.readUtf8(); | |
} catch (final IOException exception) { | |
//ignored exception | |
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) { | |
try (final BufferedSource source = Okio.buffer(Okio.source(stream))) { | |
return source.readUtf8(); | |
} catch (final IOException exception) { | |
//ignored exception | |
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 { | |
try (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 { | |
try (final BufferedSource source = Okio.buffer(Okio.source(stream))) { | |
return source.readUtf8(); | |
} | |
} | |
} |
It's only supported by API 19 and up, because it uses try-with-resources mechanism
I edited it a little bit to support android version below API 19 https://gist.github.com/hendrawd/a2a975e21799294801d2d8d9ba5eed1f
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very much it is best code reduce more much time during read file contain.