File I/O & collection frame work

Slides:



Advertisements
Similar presentations
I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Advertisements

1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Jan Java I/O Yangjun Chen Dept. Business Computing University of Winnipeg.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
Exceptions. Definition Exception: something unexpected that can occur in the execution of a program e.g., divide by zero or attempt to open a file that.
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
COMP201 Java Programming Topic 5: Input and Output Reading: Chapter 12.
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
What Is a Collection?  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
File I/O in Java CS 311, Winter File Basics Recall that a file is block structured. What does this mean? What happens when an application opens.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Java Review Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Java I/O Input: information brought to program from an external source
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
Files and Streams. Java I/O File I/O I/O streams provide data input/output solutions to the programs. A stream can represent many different kinds of sources.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
Input / Output Chapter 13.  We use files all the time  Programs are files  Documents are files  We want them to be “permanent”  To last beyond execution.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
OOP with Java, David J. Barnes Input-Output1 A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated.
JAVA I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
12-CRS-0106 REVISED 8 FEB 2013 Java Collection. 12-CRS-0106 REVISED 8 FEB 2013 Java Collection.
Input/output Input in java is stream based.A stream represents sequence of bytes or characters. Stream provides an abstract view of I/O. Stream can be.
Two Ways to Store Data in a File  Text format  Binary format.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
Java Input / Output l a modular approach to input/output: - different stream objects are connected/wrapped to handle I/O l a data stream object: a flow.
Java I/O 1. Java I/O (Input and Output) is used to process the input and produce the output based on the input. The java.io package contains all the classes.
1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Generics and file handling Presented by: Abha Kumari Neha Pradip Vhanmane Raj Visa Rashmi Kewlani Suvrat Dixit.
Java IO Exploring the java.io package and living to talk about it.
The Java IO System Different kinds of IO Different kinds of operations
Keerthi Nelaturu Url: site.uottawa.ca/~knela006
Fundamental of Java Programming
Sequential files creation & writing
Lecture 8: I/O Streams types of I/O streams Chaining Streams
CSG2H3 Object Oriented Programming
IO in java.
OO Design and Programming II I/O: Reading and Writing
Lesson 8: More File I/O February 5, 2008
Object Writing in files
University of Central Florida COP 3330 Object Oriented Programming
I/O Basics.
Chapter 13: File Input and Output
Programming in Java Files and I/O Streams
Java Programming Course
Programming in Java Lecture 11: ArrayList
Collections Framework
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Web Design & Development Lecture 8
Java Basics Introduction to Streams.
David Davenport Spring 2005
Presentation transcript:

File I/O & collection frame work

File Classes The File class in the Java IO API gives you access to the underlying file system. Using the File class you can: Check if a file or directory exists. Create a directory if it does not exist. Read the length of a file. Rename or move a file. Delete a file. Check if path is file or directory. Read list of files in a directory.

Before you can do anything with the file system or File class, you must obtain a File instance. File file = new File("c:\\data\\input-file.txt"); Check if File Exists boolean fileExists = file.exists(); Create a Directory if it Does Not Exist File file = new File("c:\\users\\java\\newdir"); boolean dirCreated = file.mkdir();

File file = new File("c:\\data\\input-file.txt"); File Length File file = new File("c:\\data\\input-file.txt"); long length = file.length(); Rename or Move File boolean success = file.renameTo(new File("c:\\new-file.txt")); Delete File boolean success = file.delete();

Stream Classes Stream Classes Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to make input and output operation in java. A stream means continuous flow of data.

Java defines two types of streams. Byte Stream : It provides a convenient means for handling input and output of byte. Character Stream : It provides a convenient means for handling input and output of characters. Character stream uses Unicode and therefore can be internationalized.

Byte Stream Classes Byte stream is defined by using two abstract class at the top of hierarchy, they are InputStream and OutputStream. These two abstract classes have several concrete classes that handle various devices such as disk files, network connection etc.

Some important Byte stream classes Description BufferedInputStream Used for Buffered Input Stream. BufferedOutputStream Used for Buffered Output Stream. DataInputStream Contains method for reading java standard data type DataOutputStream An output stream that contain method for writing java standard data type FileInputStream Input stream that reads from a file FileOutputStream Output stream that write to a file. InputStream Abstract class that describe stream input. OutputStream Abstract class that describe stream output. PrintStream Output Stream that contain print() and println() method

These classes define several key methods. Two most important are: read() : reads byte of data. write() : Writes byte of data.

FileOutputStream class The Java.io.FileOutputStream class is an output stream for writing data to a File or to a FileDescriptor. FileOutputStream class is meant for writing streams of raw bytes such as image data.

import java.io.*; class Test { public static void main(String args[]) try FileOutputstream fout=new FileOutputStream("abc.txt"); String s=“Marathwada Mitra Mandal’s Polytechnic."; byte b[]=s.getBytes(); //converting string into byte array fout.write(b); fout.close(); System.out.println("success..."); } catch(Exception e) { system.out.println(e); } }

FileInputStream The Java.io.FileInputStream class obtains input bytes from a file in a file system. FileInputStream class is meant for reading streams of raw bytes such as image data.

import java.io.*;   class SimpleRead {    public static void main(String args[])   try     FileInputStream fin=new FileInputStream("abc.txt");       int i=0;       while((i=fin.read())!=-1)      System.out.println((char)i);       }       fin.close();     } catch(Exception e) { system.out.println(e); }    }  

Character Stream Classes Character stream is also defined by using two abstract class at the top of hierarchy, they are Reader and Writer. These two abstract classes have several concrete classes that handle unicode character.

Some important Character stream classes. Description BufferedReader Handles buffered input stream. BufferedWriter Handles buffered output stream. FileReader Input stream that reads from file. FileWriter Output stream that writes to file. InputStreamReader Input stream that translate byte to character OutputStreamReader Output stream that translate character to byte. PrintWriter Output Stream that contain print() and println() method. Reader Abstract class that define character stream input Writer Abstract class that define character stream output

FileWriter class FileWriter class is used to write character-oriented data to the file. Constructors of FileWriter class Constructor Description FileWriter(String file) creates a new file. It gets file name in string. FileWriter(File file) creates a new file. It gets file name in File object.

Methods of FileWriter class Description 1) public void write(String text) writes the string into FileWriter. 2) public void write(char c) writes the char into FileWriter. 3) public void write(char[] c) writes char array into FileWriter. 4) public void flush() flushes the data of FileWriter. 5) public void close() closes FileWriter.

import java.io.*; class Simple { public static void main(String args[]) try FileWriter fw=new FileWriter("abc.txt"); fw.write(“M.M.Polytechnic"); fw.close(); } catch(Exception e) { System.out.println(e);} System.out.println("success"); } }

FileReader class Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class. Constructors of FileWriter class Constructor Description FileReader(String file) It gets filename in string. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException. FileReader(File file) It gets filename in file instance. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException.

Methods of FileReader class Description 1) public int read() returns a character in ASCII form. It returns -1 at the end of file. 2) public void close() closes FileReader.

import java.io.*; class Simple { public static void main(String args[])throws Exception FileReader fr=new FileReader("abc.txt"); int i; while((i=fr.read())!=-1) System.out.println((char)i); fr.close(); } }

Serialization and Deserialization Serialization is a process of converting an object into a sequence of bytes which can be written to a disk or database or can be sent through streams. Serialized object includes the object's data as well as information about the object's type and the types of data stored in the object. The reverse process of creating object from sequence of bytes is called deserialization. A class must implement Serializable interface present in java.io package in order to serialize its object successfully. 

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object. The writeObject() method of ObjectOutputStream class is used to serialize an Object. The readObject() method of ObjectInputStream class is used to deserialize an Object.

Collections frame work The Java Collections Framework is a collection of interfaces and classes which helps in storing and processing the data efficiently. This framework has several useful classes which have tons of useful functions which makes a programmer task super easy.

ArrayList al=new ArrayList(); Java ArrayList class uses a dynamic array for storing the elements. It extends AbstractList class and implements List interface. Java ArrayList class can contain duplicate elements. Java ArrayList class maintains insertion order. Java ArrayList allows random access because array works at the index basis. In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list. ArrayList al=new ArrayList();

Methods of Array list Method Description void add(int index, Object element) Inserts the specified element at the specified position index in this list. void clear() Removes all of the elements from this list. boolean contains(Object o) Returns true if this list contains the specified element. int indexOf(Object o) Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element. int lastIndexOf(Object o) Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element. Object remove(int index) Removes the element at the specified position in this list. Object get(int index) Returns the element at the specified position in this list. 

Date Class Java provides the Date class available in java.util package. It provides constructors and methods to deal with date and time in java. Constructors Constructor Description Date() Creates a date object representing current date and time. Date(long milliseconds) Creates a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT.

Methods Date Class Method Description boolean after(Date date) tests if current date is after the given date. boolean before(Date date) tests if current date is before the given date. Object clone() returns the clone object of current date. int compareTo(Date date) compares current date with given date. boolean equals(Date date) compares current date with given date for equality. long getTime() returns the time represented by this date object. public int getDay() Returns the day of the week represented by this date. The returned value (0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday) represents the day of the week. void setTime(long time) changes the current date and time to given time. public int getDate() Returns the day of the month represented by this Date object. The value returned is between 1 and 31 representing the day of the month

set Interface The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. It models the mathematical set abstraction.

Methods Set Interface Method Description add( ) Adds an object to the collection. clear( ) Removes all objects from the collection. contains( ) Returns true if a specified object is an element within the collection. isEmpty( ) Returns true if the collection has no elements. iterator( ) Returns an Iterator object for the collection, which may be used to retrieve an object. remove( ) Removes a specified object from the collection. size( ) Returns the number of elements in the collection.

Iterator Interface Iterator is used various collection classes. Both Iterator and ListIterator are used for iterating (looping) through elements of a collection classes such as HashMap, ArrayList, LinkedList etc. Using Iterator we can traverse in one direction (forward) while using ListIterator we can traverse the collection class on both the directions(backward and forward).

Methods Iterator Interface Description boolean hasNext() Returns true if the iteration has more elements.  Object next() Returns the next element in the iteration.  void remove() Removes from the underlying collection the last element returned by the iterator (optional operation).

map Interface The map interface describes a mapping from keys to values i.e. key and value pair. Each key and value pair is known as an entry. Map contains only unique keys. Map is useful if you have to search, update or delete elements on the basis of key.

Methods of map Interface Description public Object put(Object key, Object value) is used to insert an entry in this map. public void putAll(Map map) is used to insert the specified map in this map. public Object remove(Object key) is used to delete an entry for the specified key. public Object get(Object key) is used to return the value for the specified key. public boolean containsKey(Object key) is used to search the specified key from this map. public Set keySet() returns the Set view containing all the keys. public Set entrySet() returns the Set view containing all the keys and values.