Android read text raw resource file
If you use IOUtils from apache "commons-io" it's even easier:
InputStream is = getResources().openRawResource(R.raw.yourNewTextFile);
String s = IOUtils.toString(is);
IOUtils.closeQuietly(is); // don't forget to close your streams
Dependencies: http://mvnrepository.com/artifact/commons-io/commons-io
Maven:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
Gradle:
'commons-io:commons-io:2.4'
What if you use a character-based BufferedReader instead of byte-based InputStream?
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
while (line != null) {
...
line = reader.readLine();
}
Don't forget that readLine()
skips the new-lines!
You can use this:
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.help);
byte[] b = new byte[in_s.available()];
in_s.read(b);
txtHelp.setText(new String(b));
} catch (Exception e) {
// e.printStackTrace();
txtHelp.setText("Error: can't show help.");
}
Well with Kotlin u can do it just in one line of code:
resources.openRawResource(R.raw.rawtextsample).bufferedReader().use { it.readText() }
Or even declare extension function:
fun Resources.getRawTextFile(@RawRes id: Int) =
openRawResource(id).bufferedReader().use { it.readText() }
And then just use it straightaway:
val txtFile = resources.getRawTextFile(R.raw.rawtextsample)