

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are the key steps in read/write from/to a URL connection in java?
The URL class of the java.net package represents a Uniform Resource Locator which is used to point a resource(file or, directory or a reference) in the world wide web.
This class provides various constructors one of them accepts a String parameter and constructs an object of the URL class.
The openStream() method of this class opens a connection to the URL represented by the current object and returns an InputStream object using which you can read data from the URL.
Therefore, to read data from web page (using the URL class) −
Instantiate the java.net.URL class by passing the URL of the desired web page as a parameter to its constructor.
Invoke the openStream() method and retrieve the InputStream object.
Instantiate the Scanner class by passing the above retrieved InputStream object as a parameter.
Example
import java.io.IOException; import java.net.URL; import java.util.Scanner; public class ReadingWebPage { public static void main(String args[]) throws IOException { //Instantiating the URL class URL url = new URL("http://www.something.com/"); //Retrieving the contents of the specified page Scanner sc = new Scanner(url.openStream()); //Instantiating the StringBuffer class to hold the result StringBuffer sb = new StringBuffer(); while(sc.hasNext()) { sb.append(sc.next()); //System.out.println(sc.next()); } //Retrieving the String from the String Buffer object String result = sb.toString(); System.out.println(result); //Removing the HTML tags result = result.replaceAll("<[^>]*>", ""); System.out.println("Contents of the web page: "+result); } }
Output
<html><body><h1>Itworks!</h1></body></html> Contents of the web page: Itworks!
- Related Questions & Answers
- What are the steps to read static members in a Java class?
- What are the most basic steps to write a web driver script?
- What are the steps of key generation using RSA algorithm?
- How to read/write data from/to .properties file in Java?
- What are the different steps involved to execute a Java program?
- What are the following steps for the key generation of DES in information security?
- What are the steps to execute Flow API in Java 9?
- What are the steps to rename a file in Git?
- Read/Write Class Objects from/to File in C++
- Write a URL in a C++ program
- What are the key features of Java?
- How to read the data from a file in Java?
- What are the Steps in RSA in Information Security?
- Steps to install a new License key in SAP HANA
- How to read a specific key-value pair from a MongoDB collection?