下面的代码来 self 的 Android 应用程序。目的是从服务器读取文本文件并在 TextView 中显示它的最后 100 行。显然,只有当文本文件的行数为 2000 时,下面的代码才能正确工作。
我能想到的是,我首先需要遍历所有行来计算它们的数量,然后再次遍历以在 textview 中显示最后 100 行。我尝试过嵌套 BufferedReaders 但没有成功。有什么想法吗?
protected Void doInBackground(String...params){
URL url;
int lines = 0;
try {
//create url object to point to the file location on internet
url = new URL(params[0]);
//make a request to server
HttpURLConnection con=(HttpURLConnection)url.openConnection();
//get InputStream instance
InputStream is=con.getInputStream();
//create BufferedReader object
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line;
//read content of the file line by line
while((line=br.readLine())!=null){
if(++lines > 1900)
text+=line + "\n";
}
br.close();
}catch (Exception e) {
e.printStackTrace();
//close dialog if error occurs
if(pd!=null) pd.dismiss();
}
return null;
}
protected void onPostExecute(Void result){
//close dialog
if(pd!=null)
pd.dismiss();
TextView txtview = (TextView) findViewById(R.id.text_view);
txtview.setMovementMethod(ScrollingMovementMethod.getInstance());
//display read text in TextView
txtview.setText(text);
}
}
}
最佳答案
一种解决方案是将所有内容添加到 ArrayList
中,然后从最后一百条记录中生成文本。为了改进功能,一旦计数达到一百以上,您可以开始删除顶部的行。
这是代码 fragment :
/* Iterate File */
List<String> lst = new ArrayList<>();
String line = null;
while((line = br.readLine()) != null) {
if(lst.size() == 100) {
lst.remove(0);
}
lst.add(line);
}
br.close();
/* Make Text */
StringBuilder sb = new StringBuilder();
for(String s : lst) {
sb.append(s).append("\n");
}
text = sb.toString();
/* Clear ArrayList */
lst.clear();
关于java - 如何从服务器读取文本文件并仅显示例如textview 中的最后 100 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36179355/