user974030
user974030

Reputation: 1

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 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) {
}

Upvotes: 0

Views: 470

Answers (4)

Aerophite
Aerophite

Reputation: 215

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.

Upvotes: 0

zengsn
zengsn

Reputation: 5313

You may use this class: java.io.RandomAccessFile, http://download.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html

Upvotes: 0

JRL
JRL

Reputation: 77995

You could also directly insert into the Editable:

Editable e = textview1.getEditableText();
while ((line = MyBr.readLine()) != null) {
    e.insert(0, line + "\r\n");
}

Upvotes: 0

michaelg
michaelg

Reputation: 2692

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.

Upvotes: 1

Related Questions