How to read a text file from the last line to the first
I need this to run in reverse so that the lines appear in the reverse order of this. Is there a quick way to flip a TextView or something like that? Thanks for any help.
try {
// Create a URL for the desired page
URL url = new URL("text.txt");
// Read all the text开发者_如何学JAVA returned by the server
BufferedReader MyBr = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
line = MyBr.readLine();
TextView textview1 = (TextView) findViewById(R.id.textView1);
StringBuilder total = new StringBuilder();
while ((line = MyBr.readLine()) != null) {
total.append(line + "\r\n");}
textview1.setText(total);
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/wonderfull.ttf");
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setTypeface(tf);
MyBr.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
Since you are changing the UI in your code, this must be run on the UI thread. Of course you know that doing I/O like this on the UI thread is a no-no and can easily create ANRs. So we'll just assume this is pseudo-code. Your best bet is to reverse things as you read the stream. You could insert at the front of the StringBuilder for example.
You could also directly insert into the Editable:
Editable e = textview1.getEditableText();
while ((line = MyBr.readLine()) != null) {
e.insert(0, line + "\r\n");
}
You may use this class: java.io.RandomAccessFile, http://download.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html
I would read the file into an array or array list and then use a for loop to print it from the last index to the first.
精彩评论