13

I am saving details in out.txt file which has created a text file in data/data/new.android/files/out.txt. I am able to append information to the text, however, I am unable to read this file. I used the following procedures to read the file :

File file = new File( activity.getDir("data", Context.MODE_WORLD_READABLE), "new/android/out.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); 

Can anyone please help me out to fix this issue ?

Regards, Sunny.

2
  • what means "unable to read this file"? Commented Jul 27, 2010 at 14:58
  • I mean, I am trying to read the contents from the file out.txt Commented Jul 27, 2010 at 15:04

3 Answers 3

14

@hermy's answer uses dataIO.readLine(), which has now deprecated, so alternate solutions to this problem can be found at How can I read a text file in Android?. I personally used @SandipArmalPatil's answer...did exactly as needed.

StringBuilder text = new StringBuilder(); try { File sdcard = Environment.getExternalStorageDirectory(); File file = new File(sdcard,"testFile.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { text.append(line); text.append('\n'); } br.close() ; }catch (IOException e) { e.printStackTrace(); } TextView tv = (TextView)findViewById(R.id.amount); tv.setText(text.toString()); ////Set the text to text view. 
Sign up to request clarification or add additional context in comments.

Comments

13

You can read a line at a time with this:

FileInputStream fis; final StringBuffer storedString = new StringBuffer(); try { fis = openFileInput("out.txt"); DataInputStream dataIO = new DataInputStream(fis); String strLine = null; if ((strLine = dataIO.readLine()) != null) { storedString.append(strLine); } dataIO.close(); fis.close(); } catch (Exception e) { } 

Change the if to while to read it all.

2 Comments

openFileInput doesn't work
also readline is deprecated, so don't use above
9

Just put your file (ie. named yourfile) inside the res/raw folder (you can create if if doesn't exist) inside your project. The R.raw.yourfile resource will be automatically generated by the sdk. To obtain a String of the text file, just use the code suggested by Vovodroid in the following post: Android read text raw resource file

 String result; try { Resources res = getResources(); InputStream in_s = res.openRawResource(R.raw.yourfile); byte[] b = new byte[in_s.available()]; in_s.read(b); result = new String(b); } catch (Exception e) { // e.printStackTrace(); result = "Error: can't show file."; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.