【问题标题】:How to solve the problem "Exception in thread "main" java.io.IOException: Stream closed" for readline()?如何解决 readline() 的“线程“主”java.io.IOException:流已关闭”的问题?
【发布时间】:2021-04-29 04:36:02
【问题描述】:

这是我自己的代码。它有一个问题。此代码适用于“退出”情况,没有任何例外,但不适用于“倒计时”情况。我需要一些帮助来解决这个问题。我将 IDEA 与 java 15 一起使用。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.Date;
import java.util.Scanner;
import java.time.LocalTime;
import java.util.NoSuchElementException;


class Clock {
public static void run(long time) {
    for (long seconds = time; seconds >= 0; seconds--) {
        try {
            Thread.sleep(1000);
            System.out.println(seconds);
        } catch (InterruptedException exc) {
            System.out.println("Thread interrupted.");
        }
    }
    System.out.println("Done!");
}

public static int getTime() {
    int time = 0;
    System.out.print("Enter seconds: ");
    try (Scanner scan = new Scanner(System.in)) {
        time = scan.nextInt();
    } catch (NoSuchElementException exc) {
        System.out.println("NumberFormatException: " + exc);
    }
    return time;
}

public static void main(String args[]) throws Exception {
    BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
    for (; ;) {
        System.out.println("What type of alarm will you choose? 1 - countdown, 2 - particular time, 3 - exit: ");
        String action = scan.readLine();
            switch (action) {
                case "countdown":
                    long time = 0;
                    if (args.length == 1) {
                        time = Integer.parseInt(args[0]);
                    } else {
                        time = getTime();
                    }
                    run(time);
                break;

                case "exit":
                    System.out.println("Bye bye!");
                    System.exit(0);
                break;

            }
        }
    }
}

在我的代码编译后(上图)我得到了这个异常: 线程“主”java.io.IOException 中的异常:流已关闭

【问题讨论】:

  • 错误指向哪一行?请输入完整的堆栈跟踪
  • 您好! pastebin.com/dewyh0RsString action = scan.readLine();

标签: java


【解决方案1】:

不要关闭扫描器(尤其是在 System.in 上),因为它也会关闭底层流。

代码try (Scanner scan = new Scanner(System.in)) 在作用域结束时自动关闭扫描仪。

【讨论】:

  • @plaza-moon 当然,只需在您的try 块中定义扫描仪inside,而不是在其标题中。
【解决方案2】:

问题在于,在 getTime() 中,您正在隐式关闭 try-with-resources 中的 System.in。不要那样做。

【讨论】:

    猜你喜欢
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2019-06-09
    • 1970-01-01
    • 2022-12-12
    • 2016-04-05
    相关资源
    最近更新 更多