簡體   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