Professional Documents
Culture Documents
Java Note 4
Java Note 4
Java Note 4
3. Collection interface
4. Iterator interface
All the operations that you perform on a data such as searching, sorting, insertion,
manipulation, deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
o is optional.
2. Algorithm
Do You Know ?
o What are the two ways to iterate the elements of a collection ?
o What is the difference between ArrayList and Vector classes in collection framework?
o What is the difference between HashSet and HashMap classes in collection
framework?
o How can we sort the elements of an object. What is the difference between
Comparable and Comparator interfaces?
Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.
3. public void remove() it removes the last elements returned by the iterator. It is
rarely used.
Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.
Before generics, we can store any type of objects in collection i.e. non-generic. Now
generics, forces the java programmer to store specific type of objects.
1) Type-safety : We can hold only a single type of objects in generics. It doesnt allow to
store other objects.
1. ArrayList<String>
1. import java.util.*;
2. class TestGenerics1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10. System.out.println("element is: "+s);
11.
12. Iterator<String> itr=list.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
Test it Now
1. import java.util.*;
2. class TestGenerics2{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(1,"vijay");
6. map.put(4,"umesh");
7. map.put(2,"ankit");
8.
9. //Now use Map.Entry for Set and Iterator
10. Set<Map.Entry<Integer,String>> set=map.entrySet();
11.
12. Iterator<Map.Entry<Integer,String>> itr=set.iterator();
13. while(itr.hasNext()){
14. Map.Entry e=itr.next();//no need to typecast
15. System.out.println(e.getKey()+" "+e.getValue());
16. }
17.
18. }}
Test it Now
Output:1 vijay
2 ankit
4 umesh
Generic class
A class that can refer to any type is known as generic class. Here, we are using T type
parameter to create the generic class of specific type.
Lets see the simple example to create and use the generic class.
1. class MyGen<T>{
2. T obj;
3. void add(T obj){this.obj=obj;}
4. T get(){return obj;}
5. }
The T type indicates that it can refer to any type (like String, Integer, Employee etc.). The
type you specify for the class, will be used to store and retrieve the data.
Using generic class:
1. class TestGenerics3{
2. public static void main(String args[]){
3. MyGen<Integer> m=new MyGen<Integer>();
4. m.add(2);
5. //m.add("vivek");//Compile time error
6. System.out.println(m.get());
7. }}
Output:2
Type Parameters
The type parameters naming conventions are important to learn generics thoroughly. The
commonly type parameters are as follows:
1. T - Type
2. E - Element
3. K - Key
4. N - Number
5. V - Value
Generic Method
Like generic class, we can create generic method that can accept any type of argument.
Lets see a simple example of java generic method to print array elements. We are using
here E to denote the element.
1. import java.util.*;
2. abstract class Shape{
3. abstract void draw();
4. }
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11.
12.
13. class GenericTest{
14. //creating a method that accepts only child class of Shape
15. public static void drawShapes(List<? extends Shape> lists){
16. for(Shape s:lists){
17. s.draw();//calling method of Shape class by child class instance
18. }
19. }
20. public static void main(String args[]){
21. List<Rectangle> list1=new ArrayList<Rectangle>();
22. list1.add(new Rectangle());
23.
24. List<Circle> list2=new ArrayList<Circle>();
25. list2.add(new Circle());
26. list2.add(new Circle());
27.
28. drawShapes(list1);
29. drawShapes(list2);
30. }}
drawing rectangle
drawing circle
drawing circle
o Java ArrayList allows random access because array works at the index basis.
Constructor Description
ArrayList(Collection c) It is used to build an array list that is initialized with the elements of the colle
ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.
Method Description
void add(int index, Object It is used to insert the specified element at the specified position index i
element)
boolean addAll(Collection c) It is used to append all of the elements in the specified collection to t
this list, in the order that they are returned by the specified collection's
void clear() It is used to remove all of the elements from this list.
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the
element, or -1 if the list does not contain this element.
Object[] toArray() It is used to return an array containing all of the elements in this
correct order.
Object[] toArray(Object[] It is used to return an array containing all of the elements in this
a) correct order.
boolean add(Object o) It is used to append the specified element to the end of a list.
boolean addAll(int index, It is used to insert all of the elements in the specified collection int
Collection c) starting at the specified position.
int indexOf(Object o) It is used to return the index in this list of the first occurrence of the
element, or -1 if the List does not contain this element.
void trimToSize() It is used to trim the capacity of this ArrayList instance to be the lis
size.
Java new generic collection allows you to have only one type of object in collection. Now it is
type safe so typecasting is not required at run time.
In generic collection, we specify the type in angular braces. Now ArrayList is forced to have
only specified type of objects in it. If you try to add another type of object, it gives compile
time error.
For more information of java generics, click here Java Generics Tutorial.
1. import java.util.*;
2. class TestCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }
Test it Now
Ravi
Vijay
Ravi
Ajay
1. By Iterator interface.
2. By for-each loop.
In the above example, we have seen traversing ArrayList by Iterator. Let's see the example
to traverse ArrayList elements using for-each loop.
1. import java.util.*;
2. class TestCollection2{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. for(String obj:al)
10. System.out.println(obj);
11. }
12. }
Test it Now
Ravi
Vijay
Ravi
Ajay
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
1. import java.util.*;
2. public class TestCollection3{
3. public static void main(String args[]){
4. //Creating user-defined class objects
5. Student s1=new Student(101,"Sonoo",23);
6. Student s2=new Student(102,"Ravi",21);
7. Student s2=new Student(103,"Hanumat",25);
8. //creating arraylist
9. ArrayList<Student> al=new ArrayList<Student>();
10. al.add(s1);//adding Student class object
11. al.add(s2);
12. al.add(s3);
13. //Getting Iterator
14. Iterator itr=al.iterator();
15. //traversing elements of ArrayList object
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20. }
21. }
Test it Now
101 Sonoo 23
102 Ravi 21
103 Hanumat 25
Example of addAll(Collection c) method
1. import java.util.*;
2. class TestCollection4{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Sonoo");
10. al2.add("Hanumat");
11. al.addAll(al2);//adding second list in first list
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
Test it Now
Ravi
Vijay
Ajay
Sonoo
Hanumat
1. import java.util.*;
2. class TestCollection5{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Ravi");
10. al2.add("Hanumat");
11. al.removeAll(al2);
12. System.out.println("iterating the elements after removing the elements of al2...");
13. Iterator itr=al.iterator();
14. while(itr.hasNext()){
15. System.out.println(itr.next());
16. }
17.
18. }
19. }
Test it Now
iterating the elements after removing the elements of al2...
Vijay
Ajay
1. import java.util.*;
2. class TestCollection6{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Ravi");
10. al2.add("Hanumat");
11. al.retainAll(al2);
12. System.out.println("iterating the elements after retaining the elements of al2...");
13. Iterator itr=al.iterator();
14. while(itr.hasNext()){
15. System.out.println(itr.next());
16. }
17. }
18. }
Test it Now
iterating the elements after retaining the elements of al2...
Ravi
Java ArrayList Example: Book
Let's see an ArrayList example where we are adding books to list and printing all the books.
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class ArrayListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new ArrayList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill
",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. list.add(b1);
24. list.add(b2);
25. list.add(b3);
26. //Traversing list
27. for(Book b:list){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
29. }
30. }
31. }
Test it Now
Output:
But there are many differences between ArrayList and Vector classes that are given below.
ArrayList Vector
Legacy Classes
Early version of java did not include the Collection framework. It only defined several classes
and interface that provide method for storing objects. When Collection framework were added in
J2SE 1.2, the original classes were reengineered to support the collection interface. These classes
are also known as Legacy classes. All legacy claases and interface were redesign by JDK 5 to
support Generics.
The following are the legacy classes defined by java.util package
1. Dictionary
2. HashTable
3. Properties
4. Stack
5. Vector
Enumeration interface
boolean hasMoreElements()
Object nextElement()
Vector class
5.
6. Vector(int size)
7.
8. Vector(int size, int incr)
9.
Vector defines several legacy method. Lets see some important legacy method define
by Vector class.
Method Description
Example of Vector
import java.util.*;
ve.add(10);
ve.add(20);
ve.add(30);
ve.add(40);
ve.add(50);
ve.add(60);
Enumeration en = ve.elements();
while(en.hasMoreElements())
System.out.println(en.nextElement());
Output :
10
20
30
40
50
60
Hashtable class
5. Hashtable(int size)
Example of Hashtable
import java.util.*;
class HashTableDemo
ht.put("a",new Integer(100));
ht.put("b",new Integer(200));
ht.put("c",new Integer(300));
ht.put("d",new Integer(400));
Set st = ht.entrySet();
Iterator itr=st.iterator();
while(itr.hasNext())
Map.Entry m=(Map.Entry)itr.next();
System.out.println(itr.getKey()+" "+itr.getValue());
Output:
a 100
b 200
c 300
d 400
Hashtable HashMap
Neither key nor values can be null Both key and values can be null
Order of table remain constant over time. does not guarantee that order of map remain
constant over time.
Properties class
5. Properties(Properties default)
6. One advantage of Properties over Hashtable is that we can specify a default property that
will be useful when no value is associated with a certain key.
Output :
Java was created by James Ghosling
o A Hashtable is an array of list. Each list is known as a bucket. The position of bucket
is identified by calling the hashcode() method. A Hashtable contains values based on
the key.
o It is synchronized.
Constructor Description
Hashtable(int size) It is used to accept an integer parameter and creates a hash table that ha
an initial size specified by integer value size.
Hashtable(int size, float It is used to create a hash table that has an initial size specified by size and
fillRatio) a fill ratio specified by fillRatio.
Method Description
boolean contains(Object This method return true if some value equal to the value exist within
value) the hash table, else return false.
boolean containsValue(Object This method return true if some value equal to the value exist
value) within the hash table, else return false.
boolean containsKey(Object This method return true if some key equal to the key exists within
key) the hash table, else return false.
boolean isEmpty() This method return true if the hash table is empty; returns false if i
contains at least one key.
void rehash() It is used to increase the size of the hash table and rehashes all of it
keys.
Object get(Object key) This method return the object that contains the value associated with
the key.
Object remove(Object key) It is used to remove the key and its value. This method return the
value associated with the key.
int size() This method return the number of entries in the hash table.
1. import java.util.*;
2. class TestCollection16{
3. public static void main(String args[]){
4. Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
5.
6. hm.put(100,"Amit");
7. hm.put(102,"Ravi");
8. hm.put(101,"Vijay");
9. hm.put(103,"Rahul");
10.
11. for(Map.Entry m:hm.entrySet()){
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14. }
15. }
Test it Now
Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit
1. import java.util.*;
2. public class HashtableExample {
3. public static void main(String args[]) {
4. // create and populate hash table
5. Hashtable<Integer, String> map = new Hashtable<Integer, String>();
6. map.put(102,"Let us C");
7. map.put(103, "Operating System");
8. map.put(101, "Data Communication and Networking");
9. System.out.println("Values before remove: "+ map);
10. // Remove value for key 102
11. map.remove(102);
12. System.out.println("Values after remove: "+ map);
13. }
14. }
Output:
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class HashtableExample {
15. public static void main(String[] args) {
16. //Creating map of Books
17. Map<Integer,Book> map=new Hashtable<Integer,Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill
",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to map
23. map.put(1,b1);
24. map.put(2,b2);
25. map.put(3,b3);
26. //Traversing map
27. for(Map.Entry<Integer, Book> entry:map.entrySet()){
28. int key=entry.getKey();
29. Book b=entry.getValue();
30. System.out.println(key+" Details:");
31. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
32. }
33. }
34. }
Output:
3 Details:
103 Operating System Galvin Wiley 6
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
STACk
Stack is a subclass of Vector that implements a standard last-in, first-out
stack.
Stack only defines the default constructor, which creates an empty stack.
Stack includes all the methods defined by Vector, and adds several of its
own.
Stack( )
Apart from the methods inherited from its parent class Vector, Stack
defines the following methods
Object peek( )
2
Returns the element on the top of the stack, but does not
remove it.
Object pop( )
3
Returns the element on the top of the stack, removing it
in the process.
4
Pushes the element onto the stack. Element is also
returned.
5
Searches for element in the stack. If found, its offset from
the top of the stack is returned. Otherwise, .1 is returned.
Example
The following program illustrates several of the methods supported by this
collection
import java.util.*;
public class StackDemo {
Output
stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack
ENUMERATion
The Enumeration interface defines the methods by which you can
enumerate (obtain one at a time) the elements in a collection of objects.
boolean hasMoreElements( )
Object nextElement( )
2
This returns the next object in the enumeration as a
generic Object reference.
Example
Following is an example showing usage of Enumeration.
import java.util.Vector;
import java.util.Enumeration;
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements();
while (days.hasMoreElements()) {
System.out.println(days.nextElement());
}
}
}
Output
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
ITERATOR
Often, you will want to cycle through the elements in a collection. For
example, you might want to display each element. The easiest way to do
this is to employ an iterator, which is an object that implements either the
Iterator or the ListIterator interface.
Before you can access a collection through an iterator, you must obtain one.
Each of the collection classes provides an iterator( ) method that returns an
iterator to the start of the collection. By using this iterator object, you can
access each element in the collection, one element at a time.
Obtain an iterator to the start of the collection by calling the collection's iterator(
) method.
Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as
hasNext( ) returns true.
For collections that implement List, you can also obtain an iterator by
calling ListIterator.
boolean hasNext( )
1
Returns true if there are more elements. Otherwise,
returns false.
Object next( )
2
Returns the next element. Throws
NoSuchElementException if there is not a next element.
void remove( )
boolean hasNext( )
2
Returns true if there is a next element. Otherwise, returns
false.
boolean hasPrevious( )
3
Returns true if there is a previous element. Otherwise,
returns false.
Object next( )
4
Returns the next element. A NoSuchElementException is
thrown if there is not a next element.
int nextIndex( )
5
Returns the index of the next element. If there is not a
next element, returns the size of the list.
Object previous( )
6
Returns the previous element. A NoSuchElementException
is thrown if there is not a previous element.
int previousIndex( )
7
Returns the index of the previous element. If there is not
a previous element, returns -1.
void remove( )
9
Assigns obj to the current element. This is the element
last returned by a call to either next( ) or previous( ).
Example
Here is an example demonstrating both Iterator and ListIterator. It uses an
ArrayList object, but the general principles apply to any type of collection.
import java.util.*;
public class IteratorDemo {
public static void main(String args[]) {
// Create an array list
ArrayList al = new ArrayList();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
while(litr.hasNext()) {
Object element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
while(litr.hasPrevious()) {
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
Output
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+
StringTokenizer in Java
1. StringTokenizer
2. Methods of StringTokenizer
3. Example of StringTokenizer
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple
way to break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.
Constructor Description
1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }
Output:my
name
is
khan
The Java Scanner class breaks the input into tokens using a delimiter that is whitespace
bydefault. It provides many methods to read and parse various primitive values.
Java Scanner class is widely used to parse text for string and primitive types using regular
expression.
Java Scanner class extends Object class and implements Iterator and Closeable interfaces.
public String next() it returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and returns the
value as a string.
1. import java.util.Scanner;
2. class ScannerTest{
3. public static void main(String args[]){
4. Scanner sc=new Scanner(System.in);
5.
6. System.out.println("Enter your rollno");
7. int rollno=sc.nextInt();
8. System.out.println("Enter your name");
9. String name=sc.next();
10. System.out.println("Enter your fee");
11. double fee=sc.nextDouble();
12. System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
13. sc.close();
14. }
15. }
download this scanner example
Output:
1. import java.util.*;
2. public class ScannerTest2{
3. public static void main(String args[]){
4. String input = "10 tea 20 coffee 30 tea buiscuits";
5. Scanner s = new Scanner(input).useDelimiter("\\s");
6. System.out.println(s.nextInt());
7. System.out.println(s.next());
8. System.out.println(s.nextInt());
9. System.out.println(s.next());
10. s.close();
11. }}
Output:
10
tea
20
coffee
files
The java.io package contains nearly every class you might ever need to
perform input and output (I/O) in Java. All these streams represent an
input source and an output destination. The stream in the java.io package
supports many data such as primitives, object, localized characters, etc.
Stream
A stream can be defined as a sequence of data. There are two kinds of
Streams
Java provides strong but flexible support for I/O related to files and
networks but this tutorial covers very basic functionality related to streams
and I/O. We will see the most commonly used examples one by one
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes.
Though there are many classes related to byte streams but the most
frequently used classes are, FileInputStream and FileOutputStream.
Following is an example which makes use of these two classes to copy an
input file into an output file
Example
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
As a next step, compile the above program and execute it, which will result
in creating output.txt file with the same content as we have in input.txt. So
let's put the above code in CopyFile.java file and do the following
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes,
whereas Java Character streams are used to perform input and output for
16-bit unicode. Though there are many classes related to character streams
but the most frequently used classes are, FileReader and FileWriter.
Though internally FileReader uses FileInputStream and FileWriter uses
FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two
classes to copy an input file (having unicode characters) into an output file
Example
import java.io.*;
public class CopyFile {
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
As a next step, compile the above program and execute it, which will result
in creating output.txt file with the same content as we have in input.txt. So
let's put the above code in CopyFile.java file and do the following
$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where the
user's program can take input from a keyboard and then produce an output
on the computer screen. If you are aware of C or C++ programming
languages, then you must be aware of three standard devices STDIN,
STDOUT and STDERR. Similarly, Java provides the following three standard
streams
Standard Input This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as System.in.
Standard Output This is used to output the data produced by the user's
program and usually a computer screen is used for standard output stream and
represented as System.out.
Standard Error This is used to output the error data produced by the user's
program and usually a computer screen is used for standard error stream and
represented as System.err.
Example
import java.io.*;
public class ReadConsole {
public static void main(String args[]) throws IOException {
InputStreamReader cin = null;
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
Let's keep the above code in ReadConsole.java file and try to compile and
execute it as shown in the following program. This program continues to
read and output the same character until we press 'q'
$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q
FileInputStream
This stream is used for reading data from the files. Objects can be created
using the keyword new and there are several types of constructors
available.
Gives the number of bytes that can be read from this file
input stream. Returns an int.
There are other important input streams available, for more detail you can
refer to the following links
ByteArrayInputStream
DataInputStream
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream
would create a file, if it doesn't already exist, before opening it for output.
Once you have OutputStream object in hand, then there is a list of helper
methods, which can be used to write to stream or to do other operations on
the stream.
3
This methods writes the specified byte to the output
stream.
4
Writes w.length bytes from the mentioned byte array to
the OutputStream.
There are other important output streams available, for more detail you can
refer to the following links
ByteArrayOutputStream
DataOutputStream
Example
import java.io.*;
public class fileStreamTest {
try {
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x = 0; x < bWrite.length ; x++) {
os.write( bWrite[x] ); // writes the bytes
}
os.close();
The above code would create file test.txt and would write given numbers in
binary format. Same would be the output on the stdout screen.
File Class
FileReader Class
FileWriter Class
Directories in Java
A directory is a File which can contain a list of other files and directories.
You use File object to create directories, to list down files available in a
directory. For complete detail, check a list of all the methods which you can
call on File object and what are related to directories.
Creating Directories
There are two useful File utility methods, which can be used to create
directories
The mkdir( ) method creates a directory, returning true on success and false on
failure. Failure indicates that the path specified in the File object already exists,
or that the directory cannot be created because the entire path does not exist
yet.
The mkdirs() method creates both a directory and all the parents of the
directory.
Example
import java.io.File;
public class CreateDir {
Listing Directories
You can use list( ) method provided by File object to list down all the files
and directories available in a directory as follows
Example
import java.io.File;
public class ReadDir {
try {
// create new file object
file = new File("/tmp");
This will produce the following result based on the directories and files
available in your /tmp directory
Output
test1.txt
test2.txt
ReadDir.java
ReadDir.class
The File object represents the actual file/directory on the disk. Following is
the list of constructors to create a File object.
File(String pathname)
2
This constructor creates a new File instance by converting
the given pathname string into an abstract pathname.
3
This constructor creates a new File instance from a parent
pathname string and a child pathname string.
File(URI uri)
4
This constructor creates a new File instance by converting
the given file: URI into an abstract pathname.
Once you have File object in hand, then there is a list of helper methods
which can be used to manipulate the files.
6
Returns the absolute pathname string of this abstract
pathname.
10
Tests whether the file denoted by this abstract pathname
is a directory. Returns true if and only if the file denoted
by this abstract pathname exists and is a directory; false
otherwise.
20
Returns an array of abstract pathnames denoting the files
in the directory denoted by this abstract pathname.
32
Returns the pathname string of this abstract pathname.
This is just the string returned by the getPath() method.
Example
Following is an example to demonstrate File object
package com.tutorialspoint;
import java.io.File;
// prints
System.out.println(" is executable: "+ bool);
}
}catch(Exception e) {
// if any I/O error occurs
e.printStackTrace();
}
}
}
Output
Path of the file/test1.txt is executable: false
Path of the file/test2.txt is executable: false
JDBC
What is JDBC Driver?
JDBC drivers implement the defined interfaces in the JDBC API, for
interacting with your database server.
For example, using JDBC drivers enable you to open database connections
and to interact with it by sending SQL or database commands then
receiving results with Java.
The Java.sql package that ships with JDK, contains various classes with
their behaviours defined and their actual implementaions are done in third-
party drivers. Third party vendors implements the java.sql.Driver interface
in their database driver.
When Java first came out, this was a useful driver because most databases
only supported ODBC access but now this type of driver is recommended
only for experimental use or when no other alternative is available.
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this
kind of driver.
Type 2: JDBC-Native API
In a Type 2 driver, JDBC API calls are converted into native C/C++ API
calls, which are unique to the database. These drivers are typically provided
by the database vendors and used in the same manner as the JDBC-ODBC
Bridge. The vendor-specific driver must be installed on each client machine.
This kind of driver is extremely flexible, you don't need to install special
software on the client or server. Further, these drivers can be downloaded
dynamically.
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary
nature of their network protocols, database vendors usually supply type 4
drivers.