简体   繁体   English

如何从最后一行读取文本文件

[英]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? 有没有一种快速的方法来翻转TextView或类似的东西? 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) {
}

Since you are changing the UI in your code, this must be run on the UI thread. 由于您正在更改代码中的UI,因此必须在UI线程上运行。 Of course you know that doing I/O like this on the UI thread is a no-no and can easily create ANRs. 当然,您知道在UI线程上执行此类I / O是不行的,并且可以轻松创建ANR。 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. 例如,您可以在StringBuilder的前面插入

You could also directly insert into the Editable: 您也可以直接插入Editable中:

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

您可以使用此类:java.io.RandomAccessFile, http : //download.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html

我将文件读入数组或数组列表,然后使用for循环将其从最后一个索引打印到第一个索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM