【问题标题】:How to read text file from server and display only e.g. 100 last lines of it in textview如何从服务器读取文本文件并仅显示例如textview 中的最后 100 行
【发布时间】:2016-07-10 19:31:58
【问题描述】:

下面的代码来自我的安卓应用。目的是从服务器读取文本文件并在 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);
    }
}

}

【问题讨论】:

标签: java android bufferedreader


【解决方案1】:

一种解决方案是将所有内容添加到ArrayList,然后将您的文本从最后一百条记录中提取出来。为了改进功能,您可以在计数超过一百时开始从顶部删除行。

这里是sn-p的代码:

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

【讨论】:

  • @Vallu 欢迎您! :)
【解决方案2】:

正如接受的对Read last n lines of a HUGE file 的回复中所建议的那样,您可以估计从哪里开始读取并开始向 Guava 缓存添加行,一旦有 100 行,就会开始驱逐旧行。

或者您可以使用 Apache ReversedLinesFileReader,如对同一问题的另一个回复中所建议的那样

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

HTH

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    相关资源
    最近更新 更多