簡體   English   中英

如何在Android Studio中高效快速地從資產文件夾逐行讀取.txt文件?

[英]How to read .txt file line by line from assets folder efficiently & in a fast way in Android Studio?

我在資產文件夾中有一個文本文件,該文件有大約15000行,我想遍歷每行,我已經使用BufferedReader應用了邏輯,但是遍歷每行花費的時間太長(超過1分鍾)。

現在,我需要減少讀取每一行的時間以最大化UX。

AsyncTask<Void, String, Void> asyncTask = new AsyncTask<Void, String, Void>() {
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            appBarLayout.setVisibility(View.VISIBLE);
            viewpager.setVisibility(View.VISIBLE);
            splashScreen.setVisibility(View.GONE);
            gamesLoaded = true;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            makeRandomText(gameRandomText, "Random Text" + new Random().nextInt(1000));
        }
        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
            gamePercentage.setText(values[0]);
        }
        @Override
        protected Void doInBackground(Void... voids) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(
                        new InputStreamReader(getAssets().open("games.txt"), "UTF-8"));

                int startingCount = 0;
                // do reading, usually loop until end of file reading
                String mLine;
                while ((mLine = reader.readLine()) != null) {
                    Game gameAdded = new Game(mLine);
                    addGame(database, gameAdded);
                    startingCount++;
                    String percentage = startingCount * 100 / Constants.GAMES_COUNT + "%";
                    publishProgress(percentage);
                }
            } catch (IOException e) {
                //log the exception
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        //log the exception
                    }
                }
            }
            return null;
        }
    };

我的資產文件夾

不知道執行addGame需要多長時間,很難確定,但是我懷疑問題出在您對runOnUiThread的使用上。 您說您的文件包含15000行,因此它將創建和安排更新,UI處理程序將以您設置的方式針對每個項目運行。

您所不知道的是AsyncTask具有內置的處理進度的方式,該處理方式可以為您處理請求的反跳操作。 查看publishProgressonProgressUpdate方法以處理UI更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM