In this article, we are going to present ways to read content directly from URL in Java. We will use classes available in plain Java like
InputStream, and external libraries such as
Apache Commons IO.
This article is a part of Java I/O Series.
2. Reading Directly from a URL using
Let's start with a simple solution in plain Java. In this example we make the use of
InputStreamReader that is a bridge from byte streams to character streams. We are using this class to convert
InputStream available under
URL to a character-based stream. For better performance, we wrapped
BufferedReader that uses buffering for efficient reading of characters, arrays, and lines.
In this example, we are reading line by line from the
URL and append these Strings into
StringBuffer using platform-dependent line separator -
3. Reading content from URL with
In the next example, we used
Scanner class that can parse primitive types and strings using regular expressions.
In this example, we used
\\A delimiter that matches the beginning of the string. Then invoking
next() method returns all characters from beginning to the end of the stream.
4. Get URL content using Java 9
In Java 9 there is a nice method that reads all bytes from bytes streams. We can make use it in the following example:
Note that encoding should be always provided on conversions from bytes to characters.
5. Read URL using
Guava library provides
Resources.toString(...) method that allows us to read all content from URL into a
6. Reading URL content using
Apache Commons IO library
Apache Commons IO library comes with
IOUtils class that can be used to convert
In this article, we presented several ways to read content from the
URL in Java. We used classes available in plain Java and libraries such as
Apache Commons IO. Luckily
URL object contains method
openStream() that returns
URL actually comes to converting
InputStream to a
Examples used in this tutorial are available under our GitHub repository.