Skip to content

Instantly share code, notes, and snippets.

@ultraon

ultraon/IoUtils.java

Created May 25, 2017
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@AnkitPardyPanda AnkitPardyPanda commented Jul 6, 2017

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

@hendrawd

This comment has been minimized.

Copy link

@hendrawd hendrawd commented Aug 24, 2017

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

@hendrawd

This comment has been minimized.

Copy link

@hendrawd hendrawd commented Aug 24, 2017

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
You can’t perform that action at this time.