0

我正在使用此代码从资产中读取文本:

private void Read(String file){
        try{
            String Name = file;
            Name = Name.replaceAll("'", "");
            file = getAssets().open(Name + ".txt");
            reader = new BufferedReader(new InputStreamReader(file));
            line = reader.readLine();
            Text ="";
            while(line != null){
                line = reader.readLine();
                if (line !=null){
                    Text += line+"\n";
                    LineNumber++;
                    if(LineNumber==50){btnv.setVisibility(View.VISIBLE);break; }
                }
            }
                if (LineNumber<50){btnv.setVisibility(View.GONE);}
                 txtv.setText(Text);
        }
            catch(IOException ioe){
            ioe.printStackTrace();
        }

    }

所以我必须阅读前 50 行文本,因为文本超过 300 行,而我只知道逐行读取文件,所以如果我逐行读取 300 行,应用程序会冻结很长时间,所以我先读 50 行,然后再读 50 行,依此类推......所以在我用该代码读了前 50 行之后,我调用这个其他代码来读下一个:

private void ContinueReading(){
    if (LineNumber >= 50){
    try{
    while(line != null){
        line = reader.readLine();
        if (line !=null){
            Text += line+"\n";
            LineNumber++;
            if (LineNumber==100){break;}
            if (LineNumber==150){break;}
            if (LineNumber==200){break;}
            if (LineNumber==250){break;}
            if (LineNumber==300){break;}
            if (LineNumber==350){break;}
            if (LineNumber==400){break;}
            if (LineNumber==450){break;}
        }
        else{
            btnv.setVisibility(View.GONE);
            }
    }
         txtv.setText(Text);
    }
    catch(IOException ioe){ioe.printStackTrace();}
    }
}

但正如你所见,我保持开放状态:

        file = getAssets().open(emri + ".txt");
        reader = new BufferedReader(new InputStreamReader(file));

这不好,无论如何关闭它们并再次打开它们并从最后一行开始阅读,或者任何想法如何从前开始阅读。第 50 行,然后从第 100 行,等等。 ?

4

2 回答 2

2

这看起来是一个AsyncTask. 您甚至可以在从文件中读取文本时TextView更新文本。

    txtv.setText("");
    new MyFileReader().execute(filename);
    .
    .
    .


    // inner class
    public class MyFileReader extends AsyncTask<String, String, Void> {
        @Override
        protected Void doInBackground(String... params) {

            try{
                InputStream file = getAssets().open(params[0].replaceAll("'", "") + ".txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(file));
                String line;
                while ((line = reader.readLine()) != null) {
                    publishProgress(line + "\n");
                }
                reader.close();
            } catch(IOException ioe){
                Log.e(TAG, ioe);
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            txtv.append(values[0]);
        }
    }
于 2015-10-10T22:52:11.570 回答
1
于 2015-10-10T22:51:28.973 回答