Marcel
Marcel

Reputation: 110

Reading a large text file with over 130000 line of text

How can i read a large text file into my Application? This is my code but it does not work. My code must read a file called list.txt. The code worked only with a file with only 10.000 lines. can someone helps me? Thanks!

My code:(Worked with small files, but not with large files)

   private void largefile(){

    String strLine2="";
    wwwdf2 = new StringBuffer();
    InputStream fis2 = this.getResources().openRawResource(R.raw.list);
    BufferedReader br2 = new BufferedReader(new InputStreamReader(fis2));
    if(fis2 != null) {
        try {
            LineNumberReader lnr = new LineNumberReader(br2);
            String linenumber = String.valueOf(lnr);

            while ((strLine2 = br2.readLine()) != null) {
                wwwdf2.append(strLine2 + "\n");
            }
           // Toast.makeText(getApplicationContext(), linenumber, Toast.LENGTH_LONG).show();
            Toast.makeText(getApplicationContext(), wwwdf2, Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Upvotes: 1

Views: 949

Answers (1)

Ashok Prajapati
Ashok Prajapati

Reputation: 374

Since you are processing a large file, you should process the data in chunks . Here your file reading is fine but then you keep adding all rows in string buffer and finally passing to Toast.makeText(). It creates a big foot-print in memory. Instead you can read 100-100 lines and call Toast.makeText() to process in chunks. One more thing, use string builder instead of string buffer go avoid unwanted overhead of synchronization. You initializing wwwdf2 variable inside the method but looks it is a instance variable which I think is not required. Declare it inside method to make it's scope shorter.

Upvotes: 1

Related Questions