Reading a file returns long string without "spaces , newlines"
Good all;
I am trying to read some files (from assets) based upon list selections. The code below opens the file and retrieves the content nicely even Arabic letters. the only problem is that the text comes as a very long string without any spaces or newlines. for example the file content is: first line second line third line
the output will b开发者_Python百科e : firstlinesecondlinethirdline
the code is :
public void onItemSelected(AdapterView parent, View v,
int position, long id) {
String filename = getFileName(position);
InputStreamReader ls = null;
try {
AssetManager am = getResources().getAssets();
ls = new InputStreamReader(am.open(filename), "UTF-8");
StringBuffer sb = new StringBuffer();
while( true ) {
int c = ls.read();
if( c < 0 )
break;
if( c >= 32 )
sb.append( (char)c );
selection.setText(new String(sb));
}
} catch(IOException e) {
Log.e(LOG_APP_TAG, e.getMessage());
} finally {
if (ls != null) {
try {
ls.close();
} catch (IOException e) {
Log.e(LOG_APP_TAG, e.getMessage());
}
}
}
}
Your code has several problems :
- it is not recommended to use the key word break
- using a loop with the condition (true) and breaking it in case of something is very close to "goto programming" and should be avoided.
you could have something like
boolean finished = true;
while( !finished )
{
if( c < 0 )
finished = true;
}//while
This kind of loop is more pleasant to read to my mind, and doesn't "shock" as there is not "endless loop" when you read it.
Moreover, you should really consider using a BufferedReader to read text files. This class will provide you with lines of chars, that would give a simpler code :
BufferedReader bfr = new BufferedReader( new InputStreamReader(am.open(filename), "UTF-8"); );
StringBuffer sb = new StringBuffer();
String read = "";
while( (read=bfr.readLine()) != null )
sb.apennd( read );
BuffereReader will use a buffer to read more than one byte at a time from your file, which is much more efficient.
Btw, you try/catch/finally structure is pretty well done.
Regards, Stéphane
New line has character value of 10 (<32), so its not appended, so consider appending all characters with >0 value, hence change to
if( c <= 0 )
break;
else
sb.append( (char)c );
精彩评论