05 java language and oop part v

111
Java Language and OOP Part V By Hari Christian

Upload: harichristian

Post on 21-Jul-2016

36 views

Category:

Documents


0 download

DESCRIPTION

Java Language and OOP Part V

TRANSCRIPT

Java Language and OOP Part VBy Hari Christian

Agenda• 01 String Package• 02 Date Package• 03 Math Package• 04 How Accurate are Calculation• 05 Exception - Basic• 06 Exception - Try Catch• 07 Exception - Throw• 08 Exception - Finaly

Agenda• 09 Collections - Basic• 10 Collections - List, LinkedList and ArrayList• 11 Collections - Set, HashSet and SortedSet• 12 Collections - Helper Class• 13 Collections - Generics• 14 Collections - Map, HashMap and TreeMap• 15 I/O - Simple• 16 I/O - Advanced• 17 File

String Package

• Strings Are Immutable Objects, the key concept to understand is that once a String object is created, it can never be changed

• In Java, strings are objects

String Package

• How to create String// 1st wayString s = new String();s = "abcdef";

// 2nd wayString s = new String("abcdef");

// 3rd wayString s = "abcdef";

String Package

• Following example will explain about Immutable

String s = “Java"; // ?String s2 = s; // ?s.concat(“ Rules!!!"); // ?s.toUpperCase(); // ?s.replace('a', 'X'); // ?s = s.concat(" Rules!"); // ?

String Package

• String methods:– charAt, Returns the character located at the specified index– concat, Appends one String to the end of another– equalsIgnoreCase, Determines the equality of two Strings,

ignoring case– length, Returns the number of characters in a String– replace, Replaces occurrences of a character with a new

character– substring, Returns a part of a String– toLowerCase, Returns a String with lowercase– toUpperCase, Returns a String with uppercase– trim, Removes whitespace from the ends of a String

StringBuffer & StringBuilder

• StringBuffer and StringBuilder should be used when you have to make a lot of modifications to strings of characters

• As we discussed in the previous section, String objects are immutable, so if you choose to do a lot of manipulations with String objects, you will end up with a lot of abandoned String objects in the String pool

StringBuffer & StringBuilder

• The StringBuilder class was added in Java 5

• StringBuilder has exactly the same API as the StringBuffer class, except StringBuilder is not thread safe. In other words, its methods are not synchronized

• Sun recommends that you use StringBuilder instead of StringBuffer whenever possible because StringBuilder will run faster (and perhaps jump higher)

StringBuffer & StringBuilder

• Example:StringBuffer sb = new StringBuffer("abc");sb.append("def"); // abcdefsb.delete(2, 3); // abdefsb.insert(2, “c”); // abcdefsb.reverse(); // fedcbasb.toString(); // fedcba

Date Package

• Class related to Date:– java.util.Date, Date represents a mutable date and

time to a millisecond

– java.util.Calendar, This class provides a huge variety of methods that help you convert and manipulate dates and times

– java.text.DateFormat, used to format dates

– java.util.Locale, This class is used in conjunction with DateFormat to format dates for specific locales

Date Package

• Example getting current date:

// Current date time with DateDate now = new Date();

// Current date time with CalendarCalendar cal = Calendar.getInstance();Cal.getTime();

Date Package• Example convert Date to String and otherwise:// Format dateSimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd”);

// Convert Date to StringString dateStr = sdf.format(new Date());System.out.println(dateStr);

// Convert String to DateDate date = sdf.parse(dateStr);System.out.println(date);

Date Package• Example of Calendar:Calendar calc = new GregorianCalendar(2013, 1, 28, 13, 24, 56);System.out.println(calc.getTime()); // Thu Feb 28 13:24:56 ICT

2013int year = calendar.get(Calendar.YEAR); // 2013int month = calendar.get(Calendar.MONTH); // 1 (Jan = 0, dec = 11)int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); //

28int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); // 5int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR); // 9int weekOfMonth= calendar.get(Calendar.WEEK_OF_MONTH); // 5 int hour = calendar.get(Calendar.HOUR); // 1 (12 hour clock)int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); // 13 (24 hour clock)int minute = calendar.get(Calendar.MINUTE); // 24int second = calendar.get(Calendar.SECOND); // 56int millisecond= calendar.get(Calendar.MILLISECOND); // 0

Date Package• Example of Updating Calendar:SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");Calendar calendar = new GregorianCalendar(2013,1,28,13,24,56);System.out.println("#1. " + sdf.format(calendar.getTime())); // Update a datecalendar.set(Calendar.YEAR, 2014);calendar.set(Calendar.MONTH, 11);calendar.set(Calendar.MINUTE, 33); System.out.println("#2. " + sdf.format(calendar.getTime()));

// #1. 2013 Feb 28 13:24:56// #2. 2014 Dec 28 13:33:56

Date Package• Example of Calendar operation:SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd"); Calendar calendar = new GregorianCalendar(2013,10,28);System.out.println("Date : " + sdf.format(calendar.getTime()));// Date : 2013 Nov 28 // Add one monthcalendar.add(Calendar.MONTH, 1);System.out.println("Date : " + sdf.format(calendar.getTime()));// Date : 2013 Dec 28 // Subtract 10 dayscalendar.add(Calendar.DAY_OF_MONTH, -10);System.out.println("Date : " + sdf.format(calendar.getTime()));// Date : 2013 Dec 18

Date Package• Example of Locale:Calendar c = Calendar.getInstance();c.set(2010, 11, 14); // December 14, 2010 (month is 0-based)Date d2 = c.getTime();

Locale locIT = new Locale("it", "IT"); // ItalyLocale locPT = new Locale("pt"); // Portugal

DateFormat dfIT = DateFormat.getDateInstance(DateFormat.FULL, locIT);System.out.println("Italy " + dfIT.format(d2)); // Italy domenica 14 dicembre 2010

DateFormat dfPT = DateFormat.getDateInstance(DateFormat.FULL, locPT);System.out.println("Portugal " + dfPT.format(d2));// Portugal Domingo, 14 de Dezembro de 2010

Date PackageFormat Description ExampleG Era AD

y Year 1996 or 96

M Month in Year July or Jul or 07

w Week in Year 27

W Week in Month 2

D Day in Year 189

d Day in Month 10

F Day of Week in Month 2

E Day in Week Tuesday or Tue

a AM/PM AM or PM

H Hour in Day (0 – 23) 0

k Hour in Day (1 – 24) 24

K Hour in AM/PM (0 – 11) 0

h Hour in AM/PM (1 – 12) 12

m Minute in Hour 30

s Second in Minute 55

S Millisecond 978

z Timezone Pasific Standard Time or PST or GMT +07:00

Z Timezone -0700

Date Package• Example of Pattern:

Date Pattern Result

yyyy.MM.dd G 'at' HH:mm:ss z 2001.07.04 AD at 12:08:56 PDT

EEE, MMM d, ''yy Wed, Jul 4, '01

h:mm a 12:08 PM

hh 'o''clock' a, zzzz 12 o'clock PM, Pacific Daylight Time

K:mm a, z 0:08 PM, PDT

yyyyy.MMMMM.dd GGG hh:mm aaa 02001.July.04 AD 12:08 PM

EEE, d MMM yyyy HH:mm:ss Z Wed, 4 Jul 2001 12:08:56 -0700

yyMMddHHmmssZ 010704120856-0700

yyyy-MM-dd'T'HH:mm:ss.SSSZ 2001-07-04T12:08:56.235-0700

Math Package

public static final double E = 2.7182818284590452354; public static final double PI = 3.14159265358979323846; public static native double IEEEremainder(double, double); public static double abs(double); public static float abs(float); public static int abs(int); public static long abs(long);// returns a random number between 0.0 and 1.0 public static synchronized double random(); // rounds the argument to an integer, stored as a doublepublic static native double rint(double);

Math Package - Trigonometric

public static double toDegrees(double); public static double toRadians(double); public static native double sin(double); public static native double cos(double); public static native double tan(double); public static native double asin(double); public static native double acos(double); public static native double atan(double); public static native double atan2(double, double); public static native double exp(double); public static native double pow(double, double); public static native double log(double); public static native double sqrt(double);

Math Package – Rounding and Comparing

public static native double ceil(double); public static native double floor(double); public static double max(double, double); public static float max(float, float); public static int max(int, int); public static long max(long, long); public static double min(double, double); public static float min(float, float); public static int min(int, int); public static long min(long, long); public static long round(double); public static int round(float);

How Accurate are Calculation

• The accuracy when evaluating a result is referred to as the precision of an expression

• The precision may be expressed either as number of bits (64 bits), or as the data type of the result (double precision, meaning 64-bit floating-point format)

How Accurate are Calculation

• In Java, the precision of evaluating an operator depends on the types of its operands

• Java looks at the types of the operands around an operator and picks the biggest of what it sees: double, float, and long, in that order of preference

• Both operands are then promoted to this type, and that is the type of the result

• If there are no doubles, floats, or longs in the expression, both operands are promoted to int, and that is the type of the result

How Accurate are Calculation

• A Java compiler follows this algorithm:– If either operand is a double, do the operation in

double precision.– Otherwise, if either operand is a float, do the

operation in single precision.– Otherwise, if either operand is a long, do the

operation at long precision.– Otherwise, do the operation at 32-bit int precision.

• In summary, Java expressions end up with the type of the biggest, floatiest type (double, float, long) in the expression. They are otherwise 32-bit integers.

How Accurate are Calculation

double number = 0.0;for (int i=0; i<10; i++) {

System.out.print("number = " + total + " + 0.1 = ");

number = number + 0.1;System.out.println(“number = " + number);

}System.out.println(“grand total =“ + number);

How Accurate are Calculation

• Our expectation are:Initial Number = 0.0

Then looping until 10 timesNumber = 0.0 + 0.1 = 0.1Number = 0.1 + 0.1 = 0.2…Number = 0.9 + 0.1 = 1.0

The result is 1.0

How Accurate are Calculation• However the actual result is

– number = 0.0 + 0.1 = 0.1– number = 0.1 + 0.1 = 0.2– number = 0.2 + 0.1 = 0.30000000000000004– number = 0.30000000000000004 + 0.1 = 0.4– number = 0.4 + 0.1 = 0.5– number = 0.5 + 0.1 = 0.6– number = 0.6 + 0.1 = 0.7– number = 0.7 + 0.1 = 0.7999999999999999– number = 0.7999999999999999 + 0.1 = 0.8999999999999999– number = 0.8999999999999999 + 0.1 = 0.9999999999999999– grand total = 0.9999999999999999

How Accurate are Calculation

float number = 0.0F;for (int i=0; i<10; i++) {

System.out.print("number = " + total + " + 0.1F = ");

number = number + 0.1F;System.out.println(“number = " + number);

}System.out.println(“grand total =“ + number);

How Accurate are Calculation

• Our expectation are:Initial Number = 0.0

Then looping until 10 timesNumber = 0.0 + 0.1 = 0.1Number = 0.1 + 0.1 = 0.2…Number = 0.9 + 0.1 = 1.0

The result is 1.0

How Accurate are Calculation• However the actual result is

– number = 0.0 + 0.1F = 0.1– number = 0.1 + 0.1F = 0.2– number = 0.2 + 0.1F = 0.3– number = 0.3 + 0.1F = 0.4– number = 0.4 + 0.1F = 0.5– number = 0.5 + 0.1F = 0.6– number = 0.6 + 0.1F = 0.70000005– number = 0.70000005 + 0.1F = 0.8000001– number = 0.8000001 + 0.1F = 0.9000001– number = 0.9000001 + 0.1F = 1.0000001– grand total = 1.0000001

Exception - Basic

• We'll cover the purpose and use of exceptions following this order

• The one sentence summary is "Exceptions are like software interrupts - they are generated by error conditions like division by zero, and they divert the flow of control to a place where you have said you will handle this kind of error"

Exception - Basic

• First, we'll look at the basics of:– Why exceptions are in the language– What causes an exception (implicitly and explicitly)

• Once an exception has occurred, you'll want to know how to take steps to deal with it:– How to handle ("catch") an exception within the

method where it was thrown– Handling groups of related exceptions

Exception - Basic

• Exceptions are for changing the flow of control when some important or unexpected event, usually an error, has occurred. They divert processing to a part of the program that can try to cope with the error, or at least die gracefully

• There are many possible errors that can happen in non-trivial programs: these range from "unable to open a file" to "array subscript out of range" to "no memory left to allocate" to "division by zero"

Exception - Basic

• Two things happen when an exception is thrown:– An exception object is instantiated to record the

details of what went wrong– The run-time system then diverts the normal flow of

control, to search back up the call chain for a place where you have put a statement saying you can handle this kind of exception object

Exception - Basic

• As stated previously, exceptions occur when:– The program does something illegal (common case) – The program explicitly generates an exception by

executing the throw statement (less common case)

Exception - Basic

• Example:public static void main(String[] args) {

int i=1, j=0, k; k = i/j; // line 5 causes division-by-zero exception

}

Exception – Try Catch

• Example:public static void main(String[] args) {

try {// put potentially statement error

} catch (Exception e) {// put potentially statement handle

}}

Exception – Try Catch

• Example:public static void main(String[] args) {

try {throw new NullPointerException();

} catch (NullPointerException e) {e.printStackTrace();

}}

Exception – Try Catch

• Example:public static void main(String[] args) {

try {throw new FileNotFoundException();

} catch (NullPointerException e) {e.printStackTrace();

} // Error cause expecting catch here}

Exception – Try Catch

• Example:public static void main(String[] args) {

try {throw new FileNotFoundException();

} catch (Exception e) {// To make it short, just type Exception// But this is not recommended

}}

Exception – Try Catch

• Example:public static void main(String[] args) {

try {System.out.println(“START”);String a = “”;a.trim();System.out.println(“FINISH”);

} catch (NullPointerException e) {e.printStackTrace();

}}

Exception – Try Catch

• Example:public static void main(String[] args) {

try {System.out.println(“START”);String a;a.trim();System.out.println(“FINISH”);

} catch (NullPointerException e) {e.printStackTrace();

}}

Exception – Throwspublic class ThrowsTest {

public Integer calculate() throws Exception {return null;

}

public static void main(String[] args) {try {

ThrowsTest tt = new ThrowsTest();Integer result = tt.calculate();System.out.println(result.intValue());

} catch (Exception e) {e.printStackTrace();

}}

Exception – Finally

public static void main(String[] args) {try {

System.out.println(“TRY”);} catch (NullPointerException e) {

System.out.println(“CATCH”);} finally {

System.out.println(“FINALLY”);}

}

Exception – Finally

public static void main(String[] args) {try {

System.out.println(“START TRY”);String a;a.trim();System.out.println(“FINISH TRY”);

} catch (NullPointerException e) {System.out.println(“CATCH”);

} finally {System.out.println(“FINALLY”);

}}

Collection - Basic

• A set of collection data

• Collection is data structures

• There are 4 main data structure in Collection:– List– Set– Queue– Maps (but this is not family of Collection)

Collection - Basic

Collection - Basic

• There are a few basic operations you'll normally use with collections:– Add objects to the collection– Remove objects from the collection– Find out if an object (or group of objects) is in the

collection– Retrieve an object from the collection (without

removing it)– Iterate through the collection, looking at each element

(object) one after another

Collection - List

• Lists can contain duplicate elements

• Lists are kept in the order that elements are added

• A List cares about the index

• List is also an Interface

Collection - List

• The one thing that List has that non-lists don't have is a set of methods related to the index:– addAll(int index, Collection); – get(int index); – set(int index, E element); – add(int index, E element); – remove(int index); – indexOf(Object o); – lastIndexOf(Object o);

Collection - List

• There are 3 implementation of Lists:– ArrayList– Vector– LinkedList

Collection - ArrayList

• Think of ArrayList as a growable array

• It gives you fast iteration and fast random access

• Choose ArrayList over a LinkedList when you need fast iteration but aren't as likely to be doing a lot of insertion and deletion

Collection - ArrayList

• The time to add an element to an ArrayList is normally quick

• But when the array is full, adding another element causes a new bigger array to be allocated and the old one copied over into it

Collection - ArrayListList<String> l = new ArrayList<String>();l.add("h");l.add("a");l.add("r");l.add("i");l.add("h");System.out.println("size before = " + l.size());System.out.println(“is list contain h? = ” + l.contains("h"));l.remove("h");System.out.println("size after = " + l.size());

for(String s : l) {System.out.println(s);

}

Collection - Vector

• A Vector is basically the same as an ArrayList

• But Vector methods are synchronized for thread safety

• Choose Vector if you need synchronized in Thread because the synchronized methods add a performance hit you might not need

Collection - LinkedList

• A LinkedList is ordered by index position, like ArrayList

• LinkedList gives you new methods for adding and removing from the beginning or end (addFirst and addLast), which makes it an easy choice for implementing a stack or queue

• Keep in mind that a LinkedList may iterate more slowly than an ArrayList, but it's a good choice when you need fast insertion and deletion

Collection - Set

• A Set is a collection that has no duplicate elements

• The interface java.util.Set does not add any methods

• A List cares about the uniqueness

• Set is also an Interface

Collection - Set

• There are 3 implementation of Lists:– HashSet– LinkedHashSet– TreeSet

Collection - HashSet

• A HashSet is unsorted and unordered

• Use this class when you want a collection with no duplicates and you don't care about order when you iterate through it also you want fast retrieval

Collection - HashSet

boolean[] ba = new boolean[5];Set s = new HashSet();ba[0] = s.add("a");ba[1] = s.add(new Integer(42));ba[2] = s.add("b");ba[3] = s.add("a");ba[4] = s.add(new Object());for (int x = 0; x < ba.length; x++) System.out.print(ba[x]);System.out.println("\n");for (Object o : s) System.out.print(o + " ");

Collection - LinkedHashSet

• A LinkedHashSet is an ordered version of HashSet

• Use this class instead of HashSet when you care about the iteration order

Collection - TreeSet

• The TreeSet is one of two sorted collections (the other being TreeMap)

• The elements will be in ascending order, according to natural order

• Optionally, you can construct a TreeSet with a constructor that lets you give the collection your own rules for what the order should be by using a Comparable or Comparator

Collection - TreeSet

• TreeSet works just like HashSet, but it takes a little extra work to keep everything in sorted order

• Therefore, you will choose TreeSet when the ordering of the elements is important to you, and HashSet otherwise

• There's no sense in incurring a performance penalty if you don't need to

Collection - TreeSet

boolean[] ba = new boolean[5];Set s = new TreeSet();ba[0] = s.add("a");ba[1] = s.add(new Integer(42));ba[2] = s.add("b");ba[3] = s.add("a");ba[4] = s.add(new Object());for (int x = 0; x < ba.length; x++) System.out.print(ba[x]);System.out.println("\n");for (Object o : s) System.out.print(o + " ");

Collection - Queue

• A Queue is designed to hold a list of "to-dos," or things to be processed in some way

• Queues are typically thought of as FIFO

Collection - Map

• Map is a data structure interface that connects keys and values

• A Map cares about unique identifiers

• You map a unique key (the ID) to a specific value, where both the key and the value are, of course, objects

Collection - Map

• A set of methods related to the Map:– containsKey(Object);– containsValue(Object); – get(Object key); – put(K key, V value); – remove(Object key); – values(); // get values – keySet(); // get keys – entrySet(); // get mappings

Collection - Map

• There are 4 implementation of Lists:– HashMap– Hashtable– LinkedHashMap– TreeMap

Collection - HashMap

• The HashMap gives you an unsorted and unordered Map

• When you need a Map and you don't care about the order (when you iterate through it), then HashMap is the way to go; the other maps add a little more overhead

• HashMap allow null key and null value

Collection - HashMap

• HashMap is a supremely useful class

• Hash tables allow you store together any number of key/value pairs. Instead of storing items with index values 0, 1, 2, 3, as you would in an array, you provide the key to be associated with the object

• Then in the future, you need provide only that key again, and voila, out pops the right object

Collection - HashMapMap<String, String> phonebook = new HashMap<String, String>();

String [] names = { "Lefty", "Guarav", "Wong", "Rupamay" };String [] extns = { "4873", "4810", "3769", "0" };

for(int i=0; i< names.length; i++) {phonebook.put( names[i], extns[i] );

}

System.out.println("map: " + phonebook);

Collection - Hashtable

• Hashtable is a syncronized version of HashMap

• HashMap disallow null key and null value

Collection - LinkedHashMap

• Like its Set counterpart, LinkedHashSet, the LinkedHashMap collection maintains insertion order

• Although it will be somewhat slower than HashMap for adding and removing elements, you can expect faster iteration with a LinkedHashMap

Collection - TreeMap

• TreeMap is a sorted Map

• The elements will be in ascending order, according to natural order

• Optionally, you can construct a TreeMap with a constructor that lets you give the collection your own rules for what the order should be by using a Comparable or Comparator

Collection - TreeMapMap<String, String> phonebook = new TreeMap<String, String>();

String [] names = { "Lefty", "Guarav", "Wong", "Rupamay" };String [] extns = { "4873", "4810", "3769", "0" };

for(int i=0; i< names.length; i++) {phonebook.put( names[i], extns[i] );

}

System.out.println("map: " + phonebook);

Collection – SummaryClass Map Set List Ordered SortedHashMap X No NoHashTable X No NoTreeMap X Sorted By Natural order or

CustomLinkedHashMap X By insertion order or

last access orderNo

HashSet X No NoTreeSet X Sorted By Natural order or

CustomLinkedHashSet X By insertion order NoArrayList X By index No

Vector X By index NoLinkedList X By index NoPriorityQueue Sorted By to-do order

Collection – Helper Class

• Some helpful methods in Collections:– Sort– Binary Search– Reverse– Shuffle– Swap– Copy– Rotate– Replace All

Collection – Helper Class

public static void main(String[] args) {LinkedList <String> cs = new LinkedList<String>(); cs.add( "data" ); cs.add( "element" ); cs.add( "boolean" ); cs.add( "computer" ); cs.add( "algorithm" ); System.out.println("BEFORE = " + cs );

Collections.sort( cs ); System.out.println("AFTER = " + cs );

}

Comparable vs Comparatorjava.lang.Comparable java.util.Comparator

int objOne.compareTo(objTwo) int compare(objOne, objTwo)

ReturnsNegative, if objOne < objTwoZero, if objOne == objTwoPositive, if objOne > objTwo

Same as Comparable

You must modify the class whoseinstances you want to sort

You build a class separate from the class whose instances youwant to sort

Only one sort sequence can be created

Many sort sequences can be created

Implemented frequently in the API by:String, Wrapper classes, Date, Calendar

Meant to be implemented to sort instances of third-party classes

Collection – Generic

• Generic are most implement in Collection API

• public class HashSet <E> { }means that (to use this class) you will declare and instantiate a HashSet to work with a specific type

Example:HashSet<Date> ht = new HashSet<Date>();

Java IO• Package involving Java IO

Package Name Purposejava.io Contain 75 classes and interfaces for I/Ojava.nio API for memory-mapped I/O, non blocking I/O and file lockingjava.text Formatting text, dates, numbers and messagesjava.util.regex Pattern matchingjava.util.zip Read and write ZIP filesjava.util.logging Recording log message for later problem diagnosisjava.util.jar Read and write JAR files

javax.xml.parser Read and write XMLjavax.imageio API for image file I/O ex thumbnail, conversion, etcjavax.print Printing servicesjavax.comm Accessing serial and parallel port

javax.sound.midi API for MIDI (Musical Instrument Digital Interface) datajavax.speech API for speech recognition

Java IO

• The design philosophy for Java I/O is:– Programs that do I/O should be portable– I/O is based on streams– There are lots of small classes that do one thing

Java IO - Portability of I/OWindows Unix Java

End of line \r \n \n System.getProperty(“line.separator”)

Filename Separator

\ / File.separator

Path Names

C:\temp\\192.168.1.10\temp

/home/hari Just pass the pathnameas an argument

Data Byte Order

Little endian Varies with Hardware

Big endian

Java IO - Portability of I/O

• Example:String EOL = System.getProperty("line.separator");

String path = “C:” + File.separator + “test.txt”;

Java IO - File

• java.io.File allow you to access metadata to:– Return a File object from a String containing a

pathname– Test whether a file exists, is readable/writable, or is a

directory– Say how many bytes are in the file and when it was

last modified– Delete the file, or create directory paths– Get various forms of the file pathname

• File either can be a Directory or a File

Java IO - File

// constant:public static final char separatorChar; public static final String separator; public static final char pathSeparatorChar; public static final String pathSeparator;

// constructors: public File(String path); public File(String directory, String file); public File(File directory, String file);

Java IO - File

// about the file: public String getName(); public String getParent(); public File getParentFile(); public String getPath(); public String getAbsolutePath(); public File getAbsoluteFile(); public String getCanonicalPath(); public File getCanonicalFile();

Java IO - File

// about the file: public boolean canRead(); public boolean canWrite(); public boolean exists(); public boolean isAbsolute(); public boolean isDirectory(); public boolean isFile(); public boolean isHidden(); public long lastModified(); public long length();

Java IO - File

// about the directory public String[] list(); public String[] list(FilenameFilter); public File[] listFiles(); public File[] listFiles(FilenameFilter); public File[] listFiles(FileFilter); public static File[] listRoots(); public boolean mkdir(); public boolean mkdirs();

Java IO - File

// using temporary files public boolean createNewFile(); public boolean delete(); public void deleteOnExit(); File createTempFile(String, String);File createTempFile(String, String, File);

Java IO - File

// miscellaneous: public boolean renameTo(File); public boolean setLastModified(long); public boolean setReadOnly(); public int compareTo(File); public int compareTo(Object); public boolean equals(Object); public int hashCode(); public String toString(); public URL toURL();

Java IO - File

• Example Instantiating a FileFile file = new File("c:/data/input-file.txt");

• Check if the file existsboolean fileExists = file.exists();

• Retrieve the size of the filelong length = file.length();

Java IO - File

• Renaming or Moving a fileboolean rm = file.renameTo(new File("c:/new.txt"));

• Deleting a fileboolean del = file.delete();

• Creating a fileboolean success = file.createNewFile();

Java IO - File

• Reading list of filesFile file = new File("c:\\data"); File[] files = file.listFiles();

• Checking directory or fileboolean isDirectory = file.isDirectory();

• Making a directoryboolean dir = file.mkdir();

Java IO - Scanner

• Java.util.Scanner was introduced in Java 5

• From the first 9 years of Java, did not have console input

• There are 3 convention for console input:– 0 for standard input (in C are cin or stdin)– 1 for standard output (in C are cout or stdout or printf)– 2 for standard error (in C are stderr)

Java IO - Scanner

• Example:Scanner scan = new Scanner(System.in);int age = scan.nextInt(); // Expect int valueboolean valid = scan.nextBoolean(); short status = scan.nextShort(); double salary = scan.nextDouble(); String name = scan.next();BigInteger bigint = scan.nextBigInteger(); BigDecimal bigdec = scan.nextBigDecimal();

Java IO - Scanner

• Example:Scanner scan = new Scanner(System.in);boolean a = scan.hasNext(); boolean a = scan.hasNextBoolean(); boolean a = scan.hasNextShort(); boolean a = scan.hasNextInt(); boolean a = scan.hasNextDouble(); boolean a = scan.hasNextBigInteger(); boolean a = scan.hasNextBigDecimal();

Java IO - Scanner

• Example to read file from Scanner:Scanner scan = new Scanner(new File("C:/b.txt"));while(scan.hasNextInt()) {

int value = scan.nextInt();System.out.println(value);

}

Java IO - Printf

• Example to write to console:System.out.println(“This is output”);

// printf is used for formatting the output// %d mean format to integerint age = 27;System.out.printf("Your age is: %d \n", age );

Java IO - BufferedReader

• Example to read a file:// Source fileFile hsbcFile = new File(“C:/hsbc.txt”);

// Load into memoryBufferedReader brHsbc = new BufferedReader(new FileReader(hsbcFile));

// Read line by lineString currentLine = “”;while ((currentLine = brHsbc.readLine()) != null) {

System.out.println(currentLine);}

Java IO - FileWriter

• Example to write to file:// Create temporary file

File temp = File.createTempFile("TEMP", ".txt");// Write it

FileWriter writer = new FileWriter(temp);writer.write(“Write it to file”);writer.close();// Copy from temporary to real file

temp.deleteOnExit();FileChannel src = new FileInputStream(temp).getChannel();FileChannel dest = new FileOutputStream(outputFile).getChannel();

dest.transferFrom(src, 0, src.size());

Java IO - ZipFile

• Example to create zip file:ZipFile zipFile = new ZipFile(“C:/output.zip”);ZipParameters parameters = new ZipParameters();parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); parameters.setEncryptFiles(true);parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);parameters.setPassword(password);

zipFile.addFiles(new File(“C:/a.txt”), parameters);zipFile.addFiles(new File(“C:/b.txt”), parameters);zipFile.addFiles(new File(“C:/c.txt”), parameters);

Java IO - RandomAccessFile

• Until now we have seen how input and output is done in a serial mode

• However, sometimes we want to be able to move around inside a file and write to different locations, or read from different locations, without having to scan all the data

• Traveling in a file stream in such a manner is called "random access"

Java IO - RandomAccessFile

• Example:// R = Read, RW = Read WriteRandomAccessFile myRAF = new RandomAccessFile("C:/test.txt", "rw");

myRAF.seek(myRAF.length()); // append to end of file

myRAF.writeInt(5);

myRAF.writeInt(0xBEEF);

myRAF.writeBytes("at end.");

myRAF.close();

Java IO – Running Program

• How to execute a program from Java and read the output of that program back into your application1. Get the object representing the current run-time environment.

A static method in class java.lang.Runtime does this2. Call the exec method in the run-time object, with your

command as an argument string. Give the full path name to the executable, and make sure the executable really exists on the system. The call to exec() returns a Process object

3. Connect the output of the Process (which will be coming to you as an input stream) to an input stream reader in your program

4. You can either read individual characters from the input stream, or layer a BufferedReader on it and read a line at a time as in the code below

Java IO – Running Program

• Example:Runtime rt = Runtime.getRuntime(); // Step 1Process p = rt.exec(“chmod –R 777 /home/hari”); // Step 2// Step 3InputStreamReader isr = new InputStreamReader(p.getInputStream());BufferedReader in = new BufferedReader( isr ); // Step 4

while (in.ready()) System.out.println(in.readLine()); // The output

// Clean up p.waitFor(); in.close();

Java IO – NIO

• JDK 1.4 introduced a package called java.nio

• "NIO" stands for “New I/O" support four important features not previously well-provisioned in Java:– A non-blocking I/O facility for writing scalable servers– A file interface that supports locks and memory mapping– A pattern-matching facility based on Perl-style regular

expressions– Character-set encoders and decoders

• These features are implemented using two new concepts: buffers and channels

Java IO – NIO

// Get a Channel for the file File f = new File("email.txt"); FileInputStream fis = new FileInputStream(f); FileChannel fc = fis.getChannel(); ByteBuffer bb1 = ByteBuffer.allocate((int)f.length());

// Once you have a buffer, you can read a file int count = fc.read(bb1); System.out.println("read "+ count + " bytes from email.txt"); fc.close();

Java IO – NIO

// Get a Channel for the file FileOutputStream fos = new FileOutputStream("data.txt"); FileChannel fc = fos.getChannel(); while (true) {

// Try to get a lock FileLock lock = fc.tryLock(); if (lock !=null) {

System.out.println("got lock"); lock.release();

}}

Thank You