I have a resource file in my /res/raw/ folder (/res/raw/textfile.txt) which I am trying to read from my android app for processing.
public static void main(String[] args) { File file = new File("res/raw/textfile.txt"); FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); while (dis.available() != 0) { // Do something with file Log.d("GAME", dis.readLine()); } fis.close(); bis.close(); dis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
I have tried different path syntax but always get a java.io.FileNotFoundException error. How can I access /res/raw/textfile.txt for processing? Is File file = new File("res/raw/textfile.txt"); the wrong method in Android?
***** Answer: *****
// Call the LoadText method and pass it the resourceId LoadText(R.raw.textfile); public void LoadText(int resourceId) { // The InputStream opens the resourceId and sends it to the buffer InputStream is = this.getResources().openRawResource(resourceId); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String readLine = null; try { // While the BufferedReader readLine is not null while ((readLine = br.readLine()) != null) { Log.d("TEXT", readLine); } // Close the InputStream and BufferedReader is.close(); br.close(); } catch (IOException e) { e.printStackTrace(); } }
Note this will return nothing, but will print the contents line by line as a DEBUG
string in the log.
Resources are the additional files and static content that your code uses, such as bitmaps, layout definitions, user interface strings, animation instructions, and more. You should always externalize app resources such as images and strings from your code, so that you can maintain them independently.
Click the target app module in the Project window (while in either the Android or Project view), and then select File > New > Android resource file. Fill in the details in the dialog: File name: Type the name for the XML file (does not require the . xml suffix).
Resource Manager is a tool window for importing, creating, managing, and using resources in your app. You can open the tool window by selecting View > Tool Windows > Resource Manager from the menu bar or by selecting Resource Manager on the left side bar. Click Add to add a new resource to your project.
If you have a file in res/raw/textfile.txt
from your Activity/Widget call:
getResources().openRawResource(...)
returns an InputStream
The dots should actually be an integer found in R.raw... corresponding to your filename, possibly R.raw.textfile
(it's usually the name of the file without extension)
new BufferedInputStream(getResources().openRawResource(...));
then read the content of the file as a stream
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With