You are on page 1of 23

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-withresources 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 zero
or 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<String> list1 = new ArrayList<String>();
list1.add("Ashok");
List<String> list2 = new ArrayList<String>();
list1.add("Anil");
System.out.println("Merge both list = "+merge(list1,list2));
}
@SafeVarargs
static List<String>merge(List<String>...lists)
{
List<String>mergedList = new ArrayList<String>();
for(int i=0;i<lists.length;i++)
{
mergedList.addAll(lists[i]);
}
return mergedList;
}
}

Enhanced Number Format


Public class NumberRead
{
Public static void main(String args[])
{
int improvedInt = 10_00_000;
float improvedFloat = 10_00_000f;
long improvedLong = 10_00_000l;
double improvedDouble = 10_00_000d;
}
}

Suppressed Exception
The most common use case for encountering suppressed exceptions is
when a try-with-resources statement (which is the one type of try that does
not require a catch or finally clause according to Java Language
Specification encounters an exception within the try block and then
encounters another exception in implicitly trying to close the related
resource.
A new constructor and two new methods where added to the Throwable
class
Throwable.getSuppreseed() //return Throwable[].
Throwable.addSupressed(aThrowable);

Example
Public class DirtyResource implements AutoCloseable
{
Public void accessResource()
{
Throw new RunTimeException(Wont be access Resources);
}
@override
Public void close()
{
Throw new NullPointerException(This is a null pointer Exception);
}
}

Example Conti......
Public class UseResource
{
Public static void memberFuntion()throws Exception
{
DirtyResource resource= new DirtyResource();

try
{
resource.accessResource();
}
finally
{
resource.close();
}
}

Example Conti......
public static void main(String[] arguments) throws Exception
{
try
{
memberFunction();
}
catch(Exception ex)
{
err.println("Exception encountered: " + ex.toString());
final Throwable[] suppressedExceptions = ex.getSuppressed();
final int numSuppressed = suppressedExceptions.length;
if (numSuppressed > 0)
{
err.println("tThere are " + numSuppressed + " suppressed exceptions:");
for (final Throwable exception : suppressedExceptions)

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 oneway (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)

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 and
path related.
Listing 1. Using NIO.2 to list the files with .txt extension and their dates of
creation, last access and last update
Listing 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<Path> 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
<directory>");
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<Path> {
int numFiles = 0;
int numDirs = 0;
long sizeSum = 0;
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
System.out.println("[D] " + dir);
numDirs++;
return FileVisitResult.CONTINUE;
}
@Override

You might also like