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

How to Efficiently Read URL Content in Java?

Susan Sarandon
Susan SarandonOriginal
2024-11-02 07:05:29606browse

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>

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>

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!

Statement:
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