URLConnection Read
In this chapter you will learn:
Read a web page
The following code opens an InputStream
to
a URL and wraps it with InputStreamReader
and
BufferedReader
. After that it reads from the BufferedReader
line by line.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
/* ja va2 s .c o m*/
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("http://www.java2s.com/");
InputStream inputStream = url.openStream();
BufferedReader bufferedReader = new BufferedReader
(new InputStreamReader(inputStream));
String line = bufferedReader.readLine();
while (line != null) {
System.out.println(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The code above generates the following result.
File size from URL
import java.net.URL;
import java.net.URLConnection;
/*from j a v a2s . c o m*/
public class Main {
public static void main(String[] argv) throws Exception {
int size;
URL url = new URL("http://www.java2s.com");
URLConnection conn = url.openConnection();
size = conn.getContentLength();
if (size < 0)
System.out.println("Could not determine file size.");
else
System.out.println(size);
conn.getInputStream().close();
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » URL URI