Search code examples
javaurljava.util.scannerurlconnection

Java set timeout for URL.openStream()


I have a simple code that reads a line from a URL text file:

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

But the URL server is a bit slow and takes a few seconds to respond. Whcih I think is the reason why it throws an exception:

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) [?:?]

How can I set a timeout for my code, or convert it to a way that I can set a timeout?


Solution

  • Scanner::hasNextLine

    Always use it before using Scanner::nextLine to avoid NoSuchElementException.

    Example:

    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();
        }
    }