Home > Java > javaTutorial > How to Efficiently Read URL Content in Java?

How to Efficiently Read URL Content in Java?

Susan Sarandon
Release: 2024-11-02 07:05:29
Original
710 people have browsed it

How to Efficiently Read URL Content in Java?

Simplified Java Implementation for Reading URL Content

Unlike Groovy, Java offers a more verbose approach for extracting text content from a URL. To address this, we present two efficient solutions using Java's built-in Scanner class.

Firstly, a single-line option:

<code class="java">String out = new Scanner(new URL("http://www.google.com").openStream(), "UTF-8").useDelimiter("\A").next();</code>
Copy after login

For a slightly expanded version:

<code class="java">public static String readStringFromURL(String requestURL) throws IOException {
    try (Scanner scanner = new Scanner(new URL(requestURL).openStream(), StandardCharsets.UTF_8.toString())) {
        scanner.useDelimiter("\A");
        return scanner.hasNext() ? scanner.next() : "";
    }
}</code>
Copy after login

Both options provide a concise and efficient method for retrieving URL content as a string, without the burden of complex stream handling.

The above is the detailed content of How to Efficiently Read URL Content in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template