繁体   English   中英

如何从服务器读取文本文件并仅在textview中显示它的最后100行

[英]How to read text file from server and display only e.g. 100 last lines of it in textview

下面的代码来自我的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 ,然后从最后一百条记录中提取文本。 为了改善功能,一旦计数超过一百,就可以从顶部开始删除行。

这是代码片段:

/* 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();

根据对读取HUGE文件的最后n行的接受响应中的建议,您可以估计从何处开始读取并开始向Guava缓存添加行,一旦Guava缓存中有100行,它将开始逐出较旧的行。

或者,您也可以按照对同一问题的其他答复中的建议使用Apache ReversedLinesFileReader

或者,您可以执行shell命令('tail -n100'),如此处所述 如果您真正想要的是“ tail -f”,请考虑使用Apache Commons Tailer或Java 7+文件更改通知API

HTH

暂无
暂无

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

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