0

I am trying to make the computer read a text file full of words and add it to an ArrayList. I made it work on a regular Java application, but can't get it to work on Android. Can someone help me out?

try { FileInputStream textfl = (FileInputStream) getAssets().open("test.txt"); DataInputStream is = new DataInputStream(textfl); BufferedReader r = new BufferedReader(new InputStreamReader(is)); String strLine; while ((strLine = r.readLine()) != null) { tots.add(strLine); //tots is the array list } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } 

I keep getting a error. The text file is 587kb, so could that be a problem?

5
  • What error are you getting? Edit your question to include this! Commented Mar 13, 2012 at 0:46
  • How do you want it to be displayed? In a ListView so that each item is clickable? Or in a TextView? Commented Mar 13, 2012 at 0:54
  • I just want it added to a array list and then from there it is going to be added in a list to a text view. it says error on line 38 which is FileInputStream textfl = (FileInputStream) getAssets().open("test.txt"); 03-13 00:22:02.150: E/AndroidRuntime(480): at steve.fina.androidsm.FinalActivity.onCreate(FinalActivity.java:38) -thx btw for the responces Commented Mar 13, 2012 at 0:59
  • i use to have FileInputStream textfl =new FileInputStream("test.txt"); but when i printed the size of the array list it was 0. i posted a question and someone told me to change it to FileInputStream textfl = (FileInputStream) getAssets().open("test.txt"); the first way worked in as regular java gui Commented Mar 13, 2012 at 1:06
  • @stevenminkus please add the entire exception stacktrace to a code block in your original post Commented Mar 13, 2012 at 2:19

1 Answer 1

1

try this.

private static String readTextFile(String fileName) { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(getAssets().open(fileName))); String line; final StringBuilder buffer = new StringBuilder(); while ((line = in.readLine()) != null) { buffer.append(line).append(System.getProperty("line.separator")); } return buffer.toString(); } catch (final IOException e) { return ""; } finally { try { in.close(); } catch (IOException e) { // ignore // } } } 
Sign up to request clarification or add additional context in comments.

2 Comments

where should i located the txt files??
in the assets folder of the android application

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.