[英]How to read a text file from the last line to the first
我需要以相反的順序運行,以便行以相反的順序出現。 有沒有一種快速的方法來翻轉TextView或類似的東西? 謝謝你的幫助。
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) {
}
由於您正在更改代碼中的UI,因此必須在UI線程上運行。 當然,您知道在UI線程上執行此類I / O是不行的,並且可以輕松創建ANR。 因此,我們僅假設這是偽代碼。 最好的選擇是在閱讀信息流時逆轉事情。 例如,您可以在StringBuilder的前面插入 。
您也可以直接插入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.