Android-如何延迟bufferReader的行读取速度

问题描述 投票:0回答:1

我正在使用bufferReader逐行读取txt文件,但是我发现将当前行移至下一行的速度对我来说太快了,有人知道如何降低它的速度。我尝试将Thread.sleep(1000)放入我的代码中,但对我不起作用。

这是我的代码:

public void readFileFromAssets() throws Exception{
        InputStream instream = getAssets().open("data.txt");
        try {
            // open the file for reading
            // if file the available for reading
            if (instream != null) {
                // prepare the file for reading
                InputStreamReader inputreader = new InputStreamReader(instream);
                BufferedReader br = new BufferedReader(inputreader);

                String currentLine = "";

                while ((currentLine = br.readLine()) != null) {
                    // process the line..
                    Thread.sleep(1000)
                    if("stop".equals(currentLine)){
                        break;
                    }
                    if (!isMove(currentLine)){
                        mStepCounter+=1;
                    };
                }
            }
        } catch (Exception ex) {
            // print stack trace.
        } finally {
           // close the file.
            instream.close();
        }
    }
java io bufferedreader
1个回答
0
投票

我想您可以实现Runnable,然后实现像下面的代码中所示的方法运行:

public class Main implements Runnable {

        public void run() {

            InputStream instream = null;
            try {
                instream = new FileInputStream("C:\\Users\\es.borisov\\IdeaProjects\\tststs\\src\\main\\resources\\data.txt");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            try {
                // open the file for reading
                // if file the available for reading
                if (instream != null) {
                    // prepare the file for reading
                    InputStreamReader inputreader = new InputStreamReader(instream);
                    BufferedReader br = new BufferedReader(inputreader);

                    String currentLine = "";

                    while ((currentLine = br.readLine()) != null) {
                        System.out.println(currentLine);
                        Thread.sleep(1000);
                        if("stop".equals(currentLine)){
                            break;
                        }
                    }
                }
            } catch (Exception ex) {
                // print stack trace.
            } finally {
                // close the file.
                try {
                    instream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

用法:

Runnable task = new Main();
Thread thread = new Thread(task);
thread.start();
© www.soinside.com 2019 - 2024. All rights reserved.