Rectangle 27 0

Android read text raw resource file?


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.");
    }

@d4n3 is right, the documentation of the input stream available method states: "Returns an estimated number of bytes that can be read or skipped without blocking for more input. Note that this method provides such a weak guarantee that it is not very useful in practice"

Great solution for loading files from a resource file.

I am not sure the Inputstream.available() is the correct choice here, rather read n to a ByteArrayOutputStream untill n == -1.

This may not work for large resources. It depends on the size of the inputstream read buffer and could only return a part of the resource.

You can use this:

Note
Rectangle 27 0

Android read text raw resource file?


TextView helloTxt = (TextView)findViewById(R.id.yourTextView);
    helloTxt.setText(readTxt());
}

private String readTxt(){

 InputStream inputStream = getResources().openRawResource(R.raw.yourTextFile);
 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

 int i;
try {
i = inputStream.read();
while (i != -1)
  {
   byteArrayOutputStream.write(i);
   i = inputStream.read();
  }
  inputStream.close();
} catch (IOException e) {
 // TODO Auto-generated catch block
e.printStackTrace();
}

 return byteArrayOutputStream.toString();
}

This is another method which will definitely work, but I cant get it to read multiple text files to view in multiple textviews in a single activity, anyone can help?

Note
Rectangle 27 0

Android read text raw resource file?


TextView  tv ;
findViewById(R.id.idOfTextView);
tv.setText(readNewTxt());
private String readNewTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.yourNewTextFile);
 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

 int i;
 try {
 i = inputStream.read();
while (i != -1)
  {
   byteArrayOutputStream.write(i);
   i = inputStream.read();
   }
    inputStream.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
 e.printStackTrace();
 }

 return byteArrayOutputStream.toString();
 }

@borislemke you can do this by similar way like

Note
Rectangle 27 0

Android read text raw resource file?


BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
while (line != null) { ... }

Don't forget that readLine() skips the new-lines!

What if you use a character-based BufferedReader instead of byte-based InputStream?

Note
Rectangle 27 0

Android read text raw resource file?


// reads resources regardless of their size
public byte[] getResource(int id, Context context) throws IOException {
    Resources resources = context.getResources();
    InputStream is = resources.openRawResource(id);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    byte[] readBuffer = new byte[4 * 1024];

    try {
        int read;
        do {
            read = is.read(readBuffer, 0, readBuffer.length);
            if(read == -1) {
                break;
            }
            bout.write(readBuffer, 0, read);
        } while(true);

        return bout.toByteArray();
    }finally {
        is.close();
    }
}

    // reads a string resource
public String getStringResource(int id, Charset encoding) throws IOException {
    return new String(getResource(id, getContext()), encoding);
}

    // reads an UTF-8 string resource
public String getStringResource(int id) throws IOException {
    return new String(getResource(id, getContext()), Charset.forName("UTF-8"));
}
openRawResource()
public byte[] getResource(int id) throws IOException {
        return getResource(id, getContext());
}

And watch your error handling - don't catch and ignore exceptions when your resources must exist or something is (very?) wrong.

I dont know, but that certainly is standard. Updating examples.

or from a test case, add

Note
Rectangle 27 0

Android read text raw resource file?


InputStream is = getResources().openRawResource(R.raw.yourNewTextFile);
String s = IOUtils.toString(is);
IOUtils.closeQuietly(is); // don't forget to close your streams

If you use IOUtils from apache "commons-io" it's even easier.

Note
Rectangle 27 0

Android read text raw resource file?


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.");
    }

@d4n3 is right, the documentation of the input stream available method states: "Returns an estimated number of bytes that can be read or skipped without blocking for more input. Note that this method provides such a weak guarantee that it is not very useful in practice"

And you should not catch general Exception. Catch IOException instead.

I am not sure the Inputstream.available() is the correct choice here, rather read n to a ByteArrayOutputStream untill n == -1.

Look at the android docs for InputStream.available. If I get it right they say that it should not be used for this purpose. Who'd thought that it be that hard to read the content of a stupid file...

This may not work for large resources. It depends on the size of the inputstream read buffer and could only return a part of the resource.

You can use this:

Note
Rectangle 27 0

Android read text raw resource file?


'commons-io:commons-io:2.4'
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>
InputStream is = getResources().openRawResource(R.raw.yourNewTextFile);
String s = IOUtils.toString(is);
IOUtils.closeQuietly(is); // don't forget to close your streams

But generally, importing external 3rd party libs to avoid writing 3 more lines of code.. seem like an overkill.

If you use IOUtils from apache "commons-io" it's even easier:

Note
Rectangle 27 0

Android read text raw resource file?


BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
while (line != null) { ... }

Don't forget that readLine() skips the new-lines!

What if you use a character-based BufferedReader instead of byte-based InputStream?

Note
Rectangle 27 0

Android read text raw resource file?


// reads resources regardless of their size
public byte[] getResource(int id, Context context) throws IOException {
    Resources resources = context.getResources();
    InputStream is = resources.openRawResource(id);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    byte[] readBuffer = new byte[4 * 1024];

    try {
        int read;
        do {
            read = is.read(readBuffer, 0, readBuffer.length);
            if(read == -1) {
                break;
            }
            bout.write(readBuffer, 0, read);
        } while(true);

        return bout.toByteArray();
    }finally {
        is.close();
    }
}

    // reads a string resource
public String getStringResource(int id, Charset encoding) throws IOException {
    return new String(getResource(id, getContext()), encoding);
}

    // reads an UTF-8 string resource
public String getStringResource(int id) throws IOException {
    return new String(getResource(id, getContext()), Charset.forName("UTF-8"));
}
openRawResource()
public byte[] getResource(int id) throws IOException {
        return getResource(id, getContext());
}

And watch your error handling - don't catch and ignore exceptions when your resources must exist or something is (very?) wrong.

I dont know, but that certainly is standard. Updating examples.

or from a test case, add

Note