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!