Java IO Packages Prepared by Mrs.S.Amudha AP/SWE

Slides:



Advertisements
Similar presentations
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.
Advertisements

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
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.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
Java I/O – what does it include? Command line user interface –Initial arguments to main program –System.in and System.out GUI Hardware –Disk drives ->
Java Review 2. The Agenda The following topics were highlighted to me as issues: –File IO (Rem) –Wrappers (Rem) –Interfaces (Rem) –Asymptotic Notation.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
פיתוח מונחה עצמים – שפת JAVA קבצים. References קורס "שיטות בהנדסת תוכנה", הפקולטה למדעי המחשב, הטכניון. קורס "מערכות מידע מבוזרות", הפקולטה להנדסת תעשייה.
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/
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Text Input and Output on the Console.
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.
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.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
The Java I/O Classes and Interfaces cont’d
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.
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
1 Software 1 Java I/O. 2 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating.
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.
Exception Handling, Reading and Writing in Files, Serialization, Exceptions, Files, Streams, File Readers and Writers, Serializable SoftUni Team Technical.
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.
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.
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.
Java IO Exploring the java.io package and living to talk about it.
java.io supports console and file I/O
The Java IO System Different kinds of IO Different kinds of operations
Keerthi Nelaturu Url: site.uottawa.ca/~knela006
Fundamental of Java Programming
Lecture 8: I/O Streams types of I/O streams Chaining Streams
Java Text I/O CS140 Dick Steflik. Reader Abstract super class for character based input Subclasses: – BufferedReader – CharArrayReader – FilterReader.
IO in java.
Exception Handling, Reading and Writing in Files, Serialization,
OO Design and Programming II I/O: Reading and Writing
Lesson 8: More File I/O February 5, 2008
Object Writing in files
Strings and File I/O.
12: The Java I/O System stream model.
I/O Basics.
File.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
I/O Streams- Basics Byte Streams and Character Streams
Programming in Java Files and I/O Streams
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
I/O Streams A stream is a sequence of bytes that flow from a source to a destination In a program, we read information from an input stream and write information.
Workshop for Programming And Systems Management Teachers
Workshop for Programming And Systems Management Teachers
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Files and Streams in Java
Web Design & Development Lecture 8
Java Basics Introduction to Streams.
Exception Handling Contents
ECE 122 April 14, 2005.
EEC 484/584 Computer Networks
David Davenport Spring 2005
Presentation transcript:

Java IO Packages Prepared by Mrs.S.Amudha AP/SWE

Introduction The Java Input/Output (I/O) is a part of java.io package. The java.io package contains a relatively large number of classes The classes in the package are primarily abstract classes and stream-oriented Define methods and subclasses for allowing bytes to be read from and written to files or other input and output sources

File A File object is used to obtain or manipulate the information associated with a disk file Such as the permissions, time, date, and directory path Files are a primary source and destination for data within many programs Constructors File(String directoryPath) File(String directoryPath, String filename) File(File dirObj, String filename)

What Are Streams? Is a path of communication between the source of some information and its destination Producers and consumers of bytes Example Input stream - allows you to read data from a source Output stream - allows you to write data to a destination.

Hierarchy structure

InputStream Is used for reading the data such as a byte and array of bytes from an input source An input source can be a file, a string, or memory that may contain the data It is an abstract class that defines the programming interface for all input streams that are inherited from it An input stream is automatically opened when you create it.

InputStream hierarchy

Abstract Class InputStream Is an abstract class that defines the fundamental ways in which a destination (consumer) reads a stream of bytes from some source. The identity of the source, and the manner of the creation and transport of the bytes, is irrelevant.

ByteArray I/p Stream Example // Demonstrate ByteArrayInputStream. import java.io.*; class ByteArrayInputStreamDemo { public static void main(String args[]) throws IOException { String tmp = "abcdefghijklmnopqrstuvwxyz"; byte b[] = tmp.getBytes(); ByteArrayInputStream input1 = new ByteArrayInputStream(b); ByteArrayInputStream input2 = new ByteArrayInputStream(b, 0,3); } }

FileReader The FileReader class creates a Reader that you can use to read the contents of a file Constructor FileReader(String filePath) FileReader(File fileObj)

Example // Demonstrate FileReader. import java.io.*; class FileReaderDemo { public static void main(String args[]) throws Exception { FileReader fr = new FileReader("FileReaderDemo.java"); BufferedReader br = new BufferedReader(fr); String s; while((s = br.readLine()) != null) { System.out.println(s); } fr.close(); } }

CharArrayReader CharArrayReader is an implementation of an input stream that uses a character array as the source. This class has two constructors CharArrayReader(char array[ ]) CharArrayReader(char array[ ], int start, int numChars)

Example import java.io.*; public class CharArrayReaderDemo { public static void main(String args[]) throws IOException { String tmp = "abcdefghijklmnopqrstuvwxyz"; int length = tmp.length(); char c[] = new char[length]; tmp.getChars(0, length, c, 0); CharArrayReader input1 = new CharArrayReader(c); CharArrayReader input2 = new CharArrayReader(c, 0, 5); int i; System.out.println("input1 is:"); while((i = input1.read()) != -1) { System.out.print((char)i); } System.out.println(); System.out.println("input2 is:"); while((i = input2.read()) != -1) { System.out.print((char)i) ; } System.out.println(); } }

OutputStream Is a sibling to InputStream that is used for writing byte and array of bytes to an output source An output source can be anything such as a file, a string, or memory containing the data An output stream is automatically opened when you create it You can explicitly close an output stream with the close( ) method, or let it be closed implicitly when the object is garbage collected

OutputStream hierarchy

How Files and Streams Work

Classes and Interfaces Description BufferedInputStream It used for creating an internal buffer array. It supports the mark and reset methods. BufferedOutputStream This class used for writes byte to output stream. It implements a buffered output stream. BufferedReader This class provides read text from character input stream and buffering characters.(reads characters, arrays and lines) BufferedWriter This class provides write text from character output stream and buffering characters( writes characters, arrays and lines.) ByteArrayInputStream It contains the internal buffer and read data from the stream. ByteArrayOutputStream This class used for data is written into byte array. This is implement in output stream class.

Exceptions Classes Description Exceptions CharConversionException It provides detail message in the catch block to associated with the CharConversionException EOFException This exception indicates the end of file. FileNotFoundException When the open file's pathname does not find then this exception to be occured. InterruptedIOException When the I/O operations to interrupted from any causes then it becomes. InvalidClassException Any problems to be created with class, when the Serializing runtime to be detected. InvalidObjectException When the de-serialized objects failed then it occurs.

Reading Text from the Standard Input * Standard Input: Accessed through System.in which is used to read input from the keyboard. * Standard Output: Accessed through System.out which is used to write output to be display. * Standard Error: Accessed through System.err which is used to write error output to be display. Syntax: InputStreamReader inp = new InputStreamReader(system.in);

BufferedReader The BufferedReader class is the subclass of the Reader class. It reads character-input stream data from a memory area known as a buffer maintains state. The buffer size may be specified, or the default size may be used Constructor BufferedReader(Reader in):Creates a buffering character- input stream that uses a default-sized input buffer BufferedReader(Reader in, int sz): Creates a buffering character-input stream that uses an input buffer of the specified size.

Example Output: import java.io.*; C:\java>javacReadSta ndardIO.java C:\java>java ReadStandardIO Enter text : this is an Input Stream You entered String : C:\java> import java.io.*; public class ReadStandardIO{ public static void main(String[] args) throws IOException{ InputStreamReader inp = new InputStreamReader(System.in) BufferedReader br = new BufferedReader(inp); System.out.println("Enter text : "); String str = br.readLine(); System.out.println("You entered String : "); System.out.println(str); } }

Working With File The constructors of the File class are shown in the table: Constructor - Description File(path) - Create File object for default directory (usually where program is located). File(dirpath,fname) - Create File object for directory path given as string. File(dir, fname) - Create File object for directory. Thus the statement can be written as: File f = new File("<filename>");

Methods Description Method f.exists() Returns true if file exists. f.isFile() Returns true if this is a normal file. f.isDirectory() true if "f" is a directory. f.getName() Returns name of the file or directory. f.length() Returns number of bytes in file. f.getPath() path name.

Create a File For creating a new file File.createNewFile( ) method is used. This method returns a boolean value true if the file is created otherwise return false. If the mentioned file for the specified directory is already exist then the createNewFile() method returns the false otherwise the method creates the mentioned file and return true.

Example import java.io.*; public class CreateFile1{ public static void main(String[] args) throws IOException{ File f; f=new File("myfile.txt"); if(!f.exists()){ f.createNewFile(); System.out.println("New file \"myfile.txt\" has been created to the current directory"); } } }

Read file line by line Java supports the following I/O file streams. * FileInputstream * FileOutputStream FileInputstream: This class is a subclass of Inputstream class that reads bytes from a specified file name . The read() method of this class reads a byte or array of bytes from the file. It returns -1 when the end-of-file has been reached.

Read file line by line FileOutputStream: This class is a subclass of OutputStream that writes data to a specified file name. The write() method of this class writes a byte or array of bytes to the file. DataInputStream: This class is a type of FilterInputStream that allows you to read binary data of Java primitive data types in a portable way.

Example import java.io.*; public class ReadFile{ public static void main(String[] args) throws IOException{ File f; f=new File("myfile.txt"); if(!f.exists()&& f.length()<0) System.out.println("The specified file is not exist"); else{ FileInputStream finp=new FileInputStream(f); byte b; do{ b=(byte)finp.read(); System.out.print((char)b); } while(b!=-1); finp.close(); } } }

Write To File FileOutputStream class is used to write data to a file. FileWriter is a subclass of OutputStreamWriter class that is used to write text (as opposed to binary data) to a file The BufferedWriter class is used to write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays and strings.

Example import java.io.*; public class FileWriter{ public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter the file name to create : "); String file_name = in.readLine(); File file = new File(file_name); boolean exist = file.createNewFile(); if (!exist) { System.out.println("File already exists."); System.exit(0); } else { FileWriter fstream = new FileWriter(file_name); BufferedWriter out = new BufferedWriter(fstream); out.write(in.readLine()); out.close(); System.out.println("File created successfully."); } } }

Append To File import java.io.*; class FileWrite { public static void main(String args[]) { try{ // Create file FileWriter fstream = new FileWriter("out.txt",true); BufferedWriter out = new BufferedWriter(fstream); out.write("Hello Java"); //Close the output stream out.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } }

Getting the Size of a File import java.io.*; public class FileSize{ public static void main(String[] args) throws IOException{ System.out.print("Enter file name : "); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); File f = new File(in.readLine()); if(f.exists()){ long file_size = f.length(); System.out.println("Size of the file : " + file_size); } else{ System.out.println("File does not exists."); System.exit(0); } } }

Create Temp File import java.io.File; import java.io.FileWriter; mport java.io.BufferedWriter; import java.io.IOException; public class CTFile { public static void main(String[] args){ File tempFile = null; try { tempFile = File.createTempFile("MyFile.txt", ".tmp" ); System.out.print("Created temporary file with name "); System.out.println(tempFile.getAbsolutePath()); } catch (IOException ex) { System.err.println("Cannot create temp file: " + ex.getMessage()); } finally { if (tempFile != null) { } } } }

Example import java.io.*; public class SquareNum { public double square(double num) { return num * num; } public double getNumber() throws IOException { // create a BufferedReader using System.in InputStreamReader isr = new InputStreamReader(System.in); BufferedReader inData = new BufferedReader(isr); String str; str = inData.readLine(); return (new Double(str)).doubleValue(); } public static void main(String args[]) throws IOException { SquareNum ob = new SquareNum(); double val; System.out.println("Enter value to be squared: "); val = ob.getNumber(); val = ob.square(val); System.out.println("Squared value is " + val); } }

Serialization Serialization is the process of writing the state of an object to a byte stream Serialization is also needed to implement Remote Method Invocation (RMI) An object that implements the Serializable interface can be saved and restored by the serialization facilitie

Stream Benefits Streaming interface to I/O in Java provides a clean abstraction for a complex task Filtered stream classes allows you to dynamically build the custom streaming interface to suit your data transfer requirements. InputStream, OutputStream, Reader, and Writer classes will function properly

QUERIES