Java Reference
In-Depth Information
final Pattern isJava = Pattern . compile ( ".*\\.java$" );
final Path homeDir = Paths . get ( "/Users/ben/projects/" );
Files . find ( homeDir , 255 ,
( p , attrs ) -> isJava . matcher ( p . toString ()). find ())
. forEach ( q -> { System . out . println ( q . normalize ());});
It is possible to go even further, and construct advanced solutions based on the File
Visitor interface in java.nio.file , but that requires the developer to implement
all four methods on the interface, rather than just using a single lambda expression
as done here.
In the last section of this chapter, we will discuss Java's networking support and the
core JDK classes that enable it.
Networking
The Java platform provides access to a large number of standard networking proto‐
cols, and these make writing simple networked applications quite easy. The core of
Java's network support lives in the package java.net , with additional extensibility
provided by javax.net (and in particular, javax.net.ssl ).
One of the easiest protocols to use for building applications is HyperText Transmis‐
sion Protocol (HTTP), the protocol that is used as the basic communication proto‐
col of the Web.
HTTP
HTTP is the highest-level network protocol that Java supports out of the box. It is a
very simple, text-based protocol, implemented on top of the standard TCP/IP stack.
It can run on any network port, but is usually found on port 80.
URL is the key class—it supports URLs of the form http:// , ftp:// , file:// , and
https:// out of the box. It is very easy to use, and the simplest example of Java
HTTP support is to download a particular URL. With Java 8, this is just:
URL url = new URL ( "http://www.jclarity.com/" );
try ( InputStream in = url . openStream ()) {
Files . copy ( in , Paths . get ( "output.txt" ));
} catch ( IOException ex ) {
ex . printStackTrace ();
}
For more low-level control, including metadata about the request and response, we
can use URLConnection to give us more control, and achieve something like:
try {
URLConnection conn = url . openConnection ();
String type = conn . getContentType ();
String encoding = conn . getContentEncoding ();
Date lastModified = new Date ( conn . getLastModified ());
int len = conn . getContentLength ();
Search WWH ::




Custom Search