Java Android quickly reads the complete file

I have the following code snippet to read the full contents of a text file in a line. It works, only the problem is that ... it is very slow (the file has a length of about 1500 lines).

InputStream is = this.getResources().openRawResource(R.raw.comp_rules_glossary); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String previousLine = "start"; while ((readLine = br.readLine()) != null) { rules = rules + readLine + eol; if (previousLine.equals("")) { content = content + readLine + eol; } previousLine = readLine; } is.close(); br.close(); 

Currently, I am reading the complete file on one line at a time, and then adding it to the line. Is there a faster way to do this? I am looking for a quick way to get the whole file into a string.

+4
source share
3 answers

Use StringBuilder to create large strings.

 StringBuilder sb_rules = new StringBuilder(); StringBuilder sb_content = new StringBuilder(); while ((readLine = br.readLine()) != null) { sb_rules.append(readLine); sb_rules.append(eol); if (previousLine.equals("")) { sb_content.append(readLine); sb_content.append(eol); } previousLine = readLine; } content = sb_rules.toString(); content = sb_content.toString(); 

Why is StringBuilder with String?

The line does not allow adding. Each method that you call on String creates a new object and returns it. This is because String is immutable - it cannot change its internal state.

+3
source

I see that you already have a working solution based on Kevin's comment, but it may be useful to understand why your old code was slow.

The problem is that when concatenating strings directly using the + operator or using the concat() method, it actually creates a new string with the result of concatenation. This includes copying the entire contents of both lines that you combine. So, when you read in a file and create a content line, every time you add to it, you create another copy of everything that you still have in the content.

The solution, which I believe is what you are doing now, is to use the StringBuffer class, which is a dynamic buffer that allows you to change its contents (i.e. add new data to the end), without having to select a new String object and copy everything to it.

The main thing you should keep in mind is that strings in java are immutable. Each time you call a method in a java string that somehow changes it, a new copy of the string is actually created with the result of the modification.

+1
source

Assuming Apache Commons is working fine on Android, could you use something like this?

 InputStream is = this.getResources().openRawResource(R.raw.comp_rules_glossary); String text = IOUtils.toString(is, "UTF-8"); 

(or you can use Guava and its helper CharStreams, but it is usually more verbose)

If there is no reason why you want to avoid third-party libraries?

+1
source

All Articles