Last active
October 20, 2015 15:41
-
-
Save gtomek/62edd29aeb52345ee7d4 to your computer and use it in GitHub Desktop.
IoUtils helper methods
This file contains 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.content.Context; | |
import com.squareup.okhttp.internal.io.FileSystem; | |
import java.io.File; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import okio.BufferedSource; | |
import okio.Okio; | |
import timber.log.Timber; | |
/** | |
* Utils for I/O operations. | |
* <p/> | |
* Created by Tomek on 09/06/15. | |
*/ | |
public class IoUtils { | |
private static final String UTF_8 = "UTF-8"; | |
private static final String MARKDOWN_ASSET_ROOT = "markdown"; | |
/** | |
* Returns String representation of a file from assets folder. | |
* | |
* @param context | |
* @param fileName | |
*/ | |
public static String readStringFromAssets(Context context, final String fileName) { | |
String outputString = null; | |
InputStream inputStream = null; | |
try { | |
inputStream = context.getAssets().open(fileName); | |
int size = inputStream.available(); | |
byte[] outputBuffer = new byte[size]; | |
int readBytesSize = inputStream.read(outputBuffer); | |
outputString = new String(outputBuffer, UTF_8); | |
inputStream.close(); | |
} catch (IOException e) { | |
Timber.e("Error reading file:%s", fileName); | |
} finally { | |
if (inputStream != null) { | |
try { | |
inputStream.close(); | |
} catch (IOException e) { | |
Timber.e("Cannot close inputStream!"); | |
} | |
} | |
} | |
return outputString; | |
} | |
/** | |
* Returns String content of a Markdown file. | |
* | |
* @param context app context | |
* @param markdownFolder name of the folder type e.g. "Folder1" | |
* @param fileName actual page file name | |
*/ | |
public static String readMarkdownAssetString(final Context context, final String markdownFolder, final String fileName) { | |
return readStringFromAssets(context, | |
String.format("%s%s%s%s%s", MARKDOWN_ASSET_ROOT, File.separator, markdownFolder, File.separator, | |
fileName)); | |
} | |
/** | |
* Reads file and returns a String. | |
* | |
* @param file | |
* @throws IOException | |
*/ | |
public static String readFile(File file) throws IOException { | |
BufferedSource source = Okio.buffer(FileSystem.SYSTEM.source(file)); | |
String result = source.readUtf8(); | |
source.close(); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment