Reading a text file line by line in android [closed]
Asked Answered
G

2

14

hi i just started learning android development and i'm trying to build an app that reads text from files. i have been searching all over the internet but i don't seem to find the way to do so , so i have a few questions..

1.how to do this? what is the preferred way to read a file line by line in android?

2.where should i store the file? should it be in the raw folder or maybe in the assets folder?

so this is what i already tried: " (i think the problem may be with finding the file..)

@Override   
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.filereader);

    try {
        // open the file for reading
        InputStream fis = new FileInputStream("text.txt");

        // if file the available for reading
        if (fis != null) {

          // prepare the file for reading
          InputStreamReader chapterReader = new InputStreamReader(fis);
          BufferedReader buffreader = new BufferedReader(chapterReader);

          String line;

          // read every line of the file into the line-variable, on line at the time
          do {
             line = buffreader.readLine();
            // do something with the line 
             System.out.println(line);
          } while (line != null);

        }
        } catch (Exception e) {
            // print stack trace.
        } finally {
        // close the file.
        try {
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Gammer answered 18/6, 2014 at 17:31 Comment(3)
What's the purpose of this file? It should be stored related to that.Rabbin
What happened when you tried the code you posted? If you got an error, what was it?Monogenesis
the file has a text and i want to create an array with each line of the text. when i tried to debug it it failed on "InputStream fis = new FileInputStream("text.txt");"Gammer
L
36

Depends on what you intend to do with that file. If your goal is only to read the file, then the asset folder is the way to go. If you want to store information in that file when you are done working with it, you should put it on the device.

If you choose option number 2, you need to decide if you want other applications to read the file. More information can be found at this address:

http://developer.android.com/training/basics/data-storage/files.html

Else, you can read/write directly to the device with the standard java procedure just like you described. Though, the filepath would probably be

"/sdcard/text.txt"

EDIT:

Here's some piece of code to get started with

FileInputStream is;
BufferedReader reader;
final File file = new File("/sdcard/text.txt");

if (file.exists()) {
    is = new FileInputStream(file);
    reader = new BufferedReader(new InputStreamReader(is));
    String line = reader.readLine();
    while(line != null){
        Log.d("StackOverflow", line);
        line = reader.readLine();
    }
}

But it assumes that you know you've put the text.txt at the root of your sdcard.

If the file is in the assets folder, you have to do this:

BufferedReader reader;

try{
    final InputStream file = getAssets().open("text.txt");
    reader = new BufferedReader(new InputStreamReader(file));
    String line = reader.readLine();
    while(line != null){
        Log.d("StackOverflow", line);
        line = reader.readLine();
    }
} catch(IOException ioe){
    ioe.printStackTrace();
}
Lanark answered 18/6, 2014 at 18:3 Comment(6)
i've been trying to change the first line to: InputStream fis = new FileInputStream("/sdcard/text.txt"); but it still fails.. i think i didn't understood properly how to get that file can you show me a sort of a code sample please?Gammer
I edited the answer for your needs.Lanark
i'm a little confused what do you mean by putting the file into the sd card? i tought i should put it inside the assets folder. sorry for my ignorance..Gammer
It depends on what you want to do, if it's a file you won't touch again, you should put it in the assets folder. I will edit my answer for this caseLanark
and one last question why does the inputStream has to be final?Gammer
It doesn't HAS to, but at least this way you are sure you won't reinitialize it. More information here: https://mcmap.net/q/73273/-how-does-the-quot-final-quot-keyword-in-java-work-i-can-still-modify-an-objectLanark
D
1

Your code looks good however, you should do your file reading asynchronously. For the file path, it depends if it is a file that you bundle in your APK or a file that you download in the app data folder. Depending on what version of android you are targeting, I would use try with resources...

to read from assets you can do this in an activity:

reader = new BufferedReader(
        new InputStreamReader(getAssets().open("filename.txt")));
Dorsett answered 18/6, 2014 at 17:39 Comment(1)
Addition: after which reader.readLine() works (just do{...} until (readLine==null);. Thanks!Petronia

© 2022 - 2024 — McMap. All rights reserved.