Home  >  Article  >  Java  >  How to Read a URL\'s Content into a String in Java?

How to Read a URL\'s Content into a String in Java?

DDD
DDDOriginal
2024-11-03 14:30:30469browse

How to Read a URL's Content into a String in Java?

How to Read a URL's Content into a String in Java

Reading a URL's content into a string in Java can be a straightforward task, similar to its Groovy counterpart. Let's delve into the Java equivalent:

To achieve this in few lines of code, you can utilize Java's Scanner class:

<code class="java">String content = new Scanner(new URL(url).openStream()).useDelimiter("\A").next();</code>

This reads content from the provided URL and assigns it to the content variable.

If you prefer a more comprehensive implementation, consider the following:

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

This function accepts a URL as an argument and handles exceptions with a try-with-resources block. It ensures proper resource cleanup after use.

The above is the detailed content of How to Read a URL\'s Content into a String 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