Skip to content

Instantly share code, notes, and snippets.

@caseykulm
Created June 22, 2017 16:50
Show Gist options
  • Select an option

  • Save caseykulm/9e94460797abb0dafbfba01170fe67dd to your computer and use it in GitHub Desktop.

Select an option

Save caseykulm/9e94460797abb0dafbfba01170fe67dd to your computer and use it in GitHub Desktop.
Okio Extensions
// TODO: Actually convert the below to Kotlin
/**
* 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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment