java read content of web page

The following example use easier method to read String from InputStream in Java. It uses java.util.Scanner. It will be easy/efficient to read shorter content by using this method.
Reading content of web URL:
System.out.println("Google\n" + new Scanner(new URL("http://google.com").openStream())
                                                    .useDelimiter("\\A").next());
Reading a text file :
System.out.println("TextFile\n"+new Scanner(new File("inputFile.txt"))
                                                    .useDelimiter("\\A").next());
The regex "\\A" here matches the beginning of input source. Scanner can work not only with an InputStream source, but with  anything that implements the new (JDK version >= 1.5) java.lang.Readable interface.

No comments :

Post a Comment

Your Comment and Question will help to make this blog better...