jdkupdated 1.7 ppt

Download Jdkupdated 1.7 Ppt

If you can't read please download the document

Upload: anurag-tripathi

Post on 17-Feb-2016

224 views

Category:

Documents


3 download

DESCRIPTION

Jdkupdated

TRANSCRIPT

Introducing a New Product

JDK-1.7

1-Automatic Resource Management.2-Varargs warning errasures.3-Enhanced In number Format.4-Suppressed Exception.5-NIO

Automatic Resource Management

Automatic Resource Management, or simply . The purpose is to make it easier to work with external resources which need to be disposed or closed in case of errors or successful completion of a code block.

The old way of Resource cleanup before Java -7

.

Resource Cleanup try with Resource

.

Create Custom Resources

Notes:

1-With java 7, no need to explicit resource cleanup. Its done automatically.2-Automatic resource cleanup done when initializing resource in try-with- resources block (try() {}).3-Cleanup happens because of new interface AutoCloseable. Its close method 4-is invoked by JVM as soon as try block finishes.5-If you want to use this in custom resources, then implementing 6-AutoCloseable interface is mandatory. otherwise program will not compile.7-You are not supposed to call close() method in your code. This should be called automatically bu JVM. Calling it manually may cause unexpected results.

Varargs

Varargs introduced in jdk 1.5 . The varargs allows the method to except zeroor multiple arguments .Before varargs either we use overloaded method or take an array as the method parameter but it was not considered good because it leads to the maintenance problem.If we dont know how many arguments we will have to pass in the method,varargs is the better approach.

Advantage:We dont have to provide overloaded method so less code

Varargs Example

Class VarargsExample{Public void getValues(String val){System.out.println(Entering into get Values());for(String s:val){ System.out.println(Parameter values= +s);}}Public static void main(String args[]){VarargsExample ve = new VarargsExample();ve.getValues();ve.getValues(one,two,three);}}

Varargs warning Errasures

Class VarargsExample{public static void main(String args[]){List list1 = new ArrayList();list1.add("Ashok");List list2 = new ArrayList();list1.add("Anil");System.out.println("Merge both list = "+merge(list1,list2));}@SafeVarargsstatic Listmerge(List...lists){ListmergedList = new ArrayList();for(int i=0;i 0){err.println("tThere are " + numSuppressed + " suppressed exceptions:");for (final Throwable exception : suppressedExceptions){err.println("tt" + exception.toString());}}}}}

NIO

Java NIO (New IO) is an alternative IO API for Java (from Java 1.4), meaning alternative to the standard java io and java network API. Java nio offers a different way of working io then standar io API.There are few Core Component in NIO.1-Buffer.2-Channel.

NIO Continue.....

Buffer is a block of data that is to be written to a channel or just read from a channel. It is an object that holds data and acts as an endpoint in a NIO channel. Buffer provides a formal mechanism to access data and tracks the read and write processes.Charecteristics of buffers.1-Buffers are the basic building blocks of Java NIO.2-Buffers provides a fixed size container to read and write data.3-Every buffer is readable, but only chosen buffers are writable.4-Buffers are endpoints of Channels.5-In a read-only buffer content is not mutable but, its mark, position and limit are mutable.6-By default buffers are not thread-safe

NIO Continue.....

2-Channels -Java NIO Channels are similar to streams with a few differences: You can both read and write to a Channels. Streams are typically one-way (read or write). Channels can be read and written asynchronously. Channels always read to, or write from, a Buffer. As mentioned above, you read data from a channel into a buffer, and write data from a buffer into a channel. Here is an illustration of that:

Difference between channel and stream

A stream can be used for one-way data transfer. That is, an input stream can only transfer data from a data source to a Java program; an output stream can only transfer data from a Java program to a data sink.However, a channel provides a two-way data transfer facility.

Old Way of reading and writing Data

import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException; public class WithoutNIOExample{ public static void main(String[] args) { BufferedReader br = null; String sCurrentLine = null; try { br = new BufferedReader( new FileReader("test.txt")); while ((sCurrentLine = br.readLine()) != null) { System.out.println(sCurrentLine); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException ex) { ex.printStackTrace(); } }

New Way I/O

import java.io.IOException;import java.io.RandomAccessFile;import java.nio.ByteBuffer;import java.nio.channels.FileChannel; public class ReadFileWithFixedSizeBuffer { public static void main(String[] args) throws IOException { RandomAccessFile aFile = new RandomAccessFile ("test.txt", "r"); FileChannel inChannel = aFile.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while(inChannel.read(buffer) > 0) { buffer.flip(); for (int i = 0; i < buffer.limit(); i++) { System.out.print((char) buffer.get()); } buffer.clear(); // do something with the data and clear/compact it. } inChannel.close(); aFile.close(); }}

NIO 2

NIO 2 over come complexities nio and added new fatures Like file syatem andpath related.Listing 1. Using NIO.2 to list the files with .txt extension and their dates of creation, last access and last updateListing 2. Navigating through an entire directory tree with NIO.2.

Listing 3. Monitoring file creation events with NIO.2

NIO 2 Continues.......

import java.nio.file.*;import java.nio.file.attribute.*;import java.text.*;import java.util.*;

public class ExampleNio2_Attributes {public static void main(String[] args) throws Exception {FileSystem fs = FileSystems.getDefault();Properties props = System.getProperties();String homePath = props.get("user.home").toString();Path home = fs.getPath(homePath);System.out.println("File\t\t\tCreation Date\t\tLast Access\t\tLast Update");try (DirectoryStream flow = Files.newDirectoryStream(home, "*.txt")) {for (Path item : flow) {BasicFileAttributes attrs = Files.readAttributes(item, BasicFileAttributes.class);Date creationDate = new Date(attrs.creationTime().toMillis());Date accessDate = new Date(attrs.lastAccessTime().toMillis());Date updateDate = new Date(attrs.lastModifiedTime().toMillis());DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");System.out.format("%s\t%s\t%s\t%s%n", item, df.format(creationDate), df.format(accessDate), df.format(updateDate));}}}}

NIO 2 Continues.......

import java.io.IOException;import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;

public class ExampleNio2_Navigating {public static void main(String[] args) throws Exception {if (args.length != 1) System.out.println("Use: java ExampleNio2_Navigating ");Path root = Paths.get(args[0]);CalculateFileSizeVisitor visitor = new CalculateFileSizeVisitor();Files.walkFileTree(root, visitor);System.out.format("The given directory contains %d files spred in %d directories, occupying %.4f MB in disk", visitor.numFiles, visitor.numDirs, visitor.sizeSum / (1024.0 * 1024));}}

class CalculateFileSizeVisitor implements FileVisitor {int numFiles = 0;int numDirs = 0;long sizeSum = 0;@Overridepublic FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {System.out.println("[D] " + dir);numDirs++;return FileVisitResult.CONTINUE;}

@Overridepublic FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {System.out.println("[F]\t " + file);sizeSum += attrs.size();numFiles++;return FileVisitResult.CONTINUE;}

@Overridepublic FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {System.err.println("It was not possible to analyze the file: " + file);return FileVisitResult.TERMINATE;}

@Overridepublic FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {return FileVisitResult.CONTINUE;}}

Read more: http://mrbool.com/new-in-java-7-the-nio-2-api/24028#ixzz3n6ifUmpA

Adding functionality to custom resources