Skip to content

Instantly share code, notes, and snippets.

@ultraon
Created May 25, 2017 21:37
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ultraon/c6397dfb23de2f260f81e6946ad5adc2 to your computer and use it in GitHub Desktop.
Save ultraon/c6397dfb23de2f260f81e6946ad5adc2 to your computer and use it in GitHub Desktop.
Utils for I/O operations
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();
}
}
}
@AnkitPardyPanda
Copy link

Thank you very much it is best code reduce more much time during read file contain.

@hendrawd
Copy link

It's only supported by API 19 and up, because it uses try-with-resources mechanism

@hendrawd
Copy link

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