URL.openStream()扫描程序的Java设置超时:: hasNextLine

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

我有一个简单的代码,可从URL文本文件读取一行:

url = new URL(address);
Scanner s = new Scanner(url.openStream());
s.nextLine();

但是URL服务器有点慢,需要花费几秒钟的时间进行响应。我认为这是它引发异常的原因:

java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1651) ~[?:?]
    at process.RunMe(MyFile2.java:115) [classes/:?]
    at process.Detect(MyFile2.java:31) [classes/:?]
    at Scheduler.PostHandler$3.run(MyFile.java:160) [classes/:?]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) [?:?]
    at java.util.concurrent.FutureTask.run(FutureTask.java:264) [?:?]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) [?:?]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) [?:?]
    at java.lang.Thread.run(Thread.java:834) [?:?]

如何为我的代码设置超时,或将其转换为可以设置超时的方式?

java url java.util.scanner urlconnection
1个回答
1
投票

Scanner::hasNextLine

在使用Scanner::nextLine之前总是使用它以避免NoSuchElementException

示例:

import java.io.IOException;
import java.net.URL;
import java.util.Scanner;

public class ReadURL {
    public static void main(String[] args) throws IOException {
        URL url = new URL("http://www.example.com/");
        Scanner s = new Scanner(url.openStream());
        while (s.hasNextLine()) {
            String str = s.nextLine();
            System.out.println(str);
        }
        s.close();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.