从BufferedReader读取特定持续时间 [英] Read from BufferedReader for a specific Duration

查看:169
本文介绍了从BufferedReader读取特定持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在从BufferedReader中读取内容。一切顺利,直到我添加一个条件。我需要从BufferedReader中读取特定的持续时间。

So, I'm reading from a BufferedReader. Everything goes fine, until I add one condition. I need to read from BufferedReader for a specific duration of time.

这就是我现在正在做的事情。

This is what I'm doing right now.

while ((line = br.readLine()) != null
                    && System.currentTimeMillis() - start < maxReadTime.toMillis()) { 
    // doingSomethingHere()
}

问题:即使时间已过,InputStream仍处于活动状态。
例如-maxReadTime是30秒。输入持续20秒。在接下来的12秒钟内,没有任何活动。现在,当下一个输入到达时,流将打开并仅在读取输入后关闭。但是,我不处理此输入,因为while循环终止。

The problem: InputStream is active even after the time has elapsed. For example - maxReadTime is 30 seconds. the input keeps coming in 20 seconds. For the next 12 seconds, there's no activity. Now when the next input arrives, the stream is open and closes only after it has read the input. However, I don't process this input because while loop terminates.

我期望或需要的是:Stream将在30秒后关闭。也就是说,当输入到达第32秒时,流关闭并且不监听任何输入。

What I expected or what I need: is Stream will close at 30 seconds. That is when the input arrives at 32nd second, the stream is closed and not listening to any input.

我对ExecutorService不太了解。我不确定这是否是正确的方法。

I know vaguely about ExecutorService. I'm not sure if that's the correct way to go.

推荐答案

基本上,您必须在调用 readLine()通过调用方法 ready(),对于 InputStream 检查 available()方法,该方法返回如何不加阻塞地读取字节。

Basically you have to check if buffer is ready before call readLine() by calling method ready(), for InputStream check available() method which returns how may bytes you can read without block.

这里有个例子

import java.io.*;
import java.time.Duration;

public class Main {

    public static void main(String[] args) {
        final InputStream in =  System.in; //new FileInputStream(new File("/tmp/x"));
        final String out = readInput(in, Duration.ofSeconds(5));
        System.out.printf("m=main, status=complete, out=%s%n", out);
    }

    public static String readInput(InputStream in, Duration duration) {
        final long timestamp = System.currentTimeMillis();
        final BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        final StringBuilder out = new StringBuilder();
        try {
            String line = null;
            while (true){
                if(Duration.ofMillis(System.currentTimeMillis() - timestamp).compareTo(duration) >=0 ){
                    System.out.println("m=readInput, status=timeout");
                    break;
                }
                if(!reader.ready()){
                    System.out.println("m=readInput, status=not ready");
                    sleep(1000);
                    continue;
                }
                line = reader.readLine();
                if(line == null){
                    System.out.println("m=readInput, status=null line");
                    break;
                }
                out.append(line);
                out.append('\n');
                System.out.printf("m=readInput status=read, line=%s%n" , line);
            }
            return out.toString();
        } catch (IOException e){
            throw new RuntimeException(e);
        } finally {
            System.out.println("m=readInput, status=complete");
        }
    }

    static void sleep(int millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {}
    }

}

如果您想在后台执行此操作,可以按照以下示例

If you wanna do this in background you can follow this example

package com.mageddo;

import java.io.*;
import java.util.concurrent.*;

public class Main {

public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        final InputStream in =  System.in; //new FileInputStream(new File("/tmp/x"));
        final StringBuilder out = new StringBuilder();
        final ExecutorService executor = Executors.newFixedThreadPool(1);
        final Future<String> promise = executor.submit(() -> readInput(in, out));
        try {
            final String result = promise.get(5, TimeUnit.SECONDS);
            System.out.printf("m=main, status=success, result=%s%n", result);
        } catch (TimeoutException e) {
            System.out.println("m=main, status=timeout");
            in.close();
            promise.cancel(true);
            System.out.println("Failed output: " + promise.get());
            e.printStackTrace();
        } finally {
            executor.shutdown();
            System.out.println("m=main, status=shutdown, out=" + out);
        }
    }

    public static String readInput(InputStream in, StringBuilder out) {
        final BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        try {
            String line = null;
            while (true){
                if(Thread.currentThread().isInterrupted()){
                    System.out.println("m=readInput status=interrupt signal");
                    break;
                }
                if(!reader.ready()){
                    System.out.println("m=readInput, status=not ready");
                    sleep(1000);
                    continue;
                }
                line = reader.readLine();
                if(line == null){
                    System.out.println("m=readInput, status=null line");
                    break;
                }
                out.append(line);
                out.append('\n');
                System.out.printf("m=readInput status=read, line=%s%n" , line);
            }
            return out.toString();
        } catch (IOException e){
            throw new RuntimeException(e);
        } finally {
            System.out.println("m=readInput, status=complete");
        }
    }

    static void sleep(int millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

}

请参阅参考文件

这篇关于从BufferedReader读取特定持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆