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!