File.

Slides:



Advertisements
Similar presentations
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. 2 Operating System Application #1 Application #2 Java Virtual Machine #1 Local Memory Shared Memory Threads.
Advertisements

I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
1 Streams and Input/Output Files Part 3. 2 Handling Primitive Data Types The basic input and output streams provide read/write methods that can be used.
1 Streams and Input/Output Files Part I. 2 Introduction So far we have used variables and arrays for storing data inside the programs. This approach poses.
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
1 Text File I/O  I/O streams  Opening a text file for reading  Closing a stream  Reading a text file  Writing and appending to a text file.
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.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
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.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Io package as Java’s basic I/O system continue’d.
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/
Java File I/O (Continued). File I/O in Java Like every other programming language, Java supports the writing to and reading from different files with.
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.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
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.
Chapter 17 Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams  Use JFileChooser F Text Input.
1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.
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.
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.
I / O in java. java.io BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter ByteArrayInputStream ByteArrayOutputStream CharArrayReader.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
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.
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.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
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.
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 Programming: Advanced Topics 1 Input/Output and Serialization.
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.
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.
Fundamental of Java Programming
Lecture 8: I/O Streams types of I/O streams Chaining Streams
IO in java.
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
Chapter 17 Input and Output
OO Design and Programming II I/O: Reading and Writing
Ch14 Files and Streams OBJECTIVES
Object Writing in files
University of Central Florida COP 3330 Object Oriented Programming
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
Chapter 17 Binary I/O 1.
I/O Streams- Basics Byte Streams and Character Streams
Programming in Java Files and I/O Streams
Java Programming Course
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Java Basics Introduction to Streams.
OO Java Programming Input Output.
David Davenport Spring 2005
Presentation transcript:

File

File Although most of the classes defined by java.io operate on streams, the File class does not. It deals directly with files and the file system. That is, the File class does not specify how information is retrieved from or stored in files; it describes the properties of a file itself. 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, and to navigate subdirectory hierarchies.

Constructors of File File(String directoryPath) File(String directoryPath, String filename) File(File dirObj, String filename) Example: File f1 = new File(“C:/"); File f2 = new File(“C:/", "autoexec.bat"); File f3 = new File(f1, "autoexec.bat");

File methods

Basics of I/O Streams

Introduction Most real applications of Java are not text-based, console programs. Java’s support for console I/O is limited. Text-based console I/O is not very important to Java programming. Java does provide strong, flexible support for I/O as it relates to files and networks.

Streams Java implements streams within class hierarchies defined in the java.io package. A stream is a sequence of data. A stream is linked to a physical device by the Java I/O system. All streams behave in the same manner, even if the actual physical devices to which they are linked differ. An I/O Stream represents an input source or an output destination.

I/O Streams A stream can represent many different kinds of sources and destinations – disk files, devices, other programs, a network socket, and memory arrays Streams support many different kinds of data – simple bytes, primitive data types, localized characters, and objects Some streams simply pass on data; others manipulate and transform the data in useful ways.

Reading information into a program. Input Stream A program uses an input stream to read data from a source, one item at a time. Reading information into a program.

Writing information from a program. Output Stream A program uses an output stream to write data to a destination, one item at time: Writing information from a program.

Types of Streams Java defines two different types of Streams- Byte Streams Character Streams Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used, for example, when reading or writing binary data. Character streams provide a convenient means for handling input and output of characters. In some cases, character streams are more efficient than byte streams.

Byte Streams Programs use byte streams to perform input and output of 8-bit bytes. Byte streams are defined by using two class hierarchies. At the top, there are two abstract classes: InputStream and OutputStream. The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement. Two of the most important methods are read( )and write( ), which, respectively, read and write bytes of data. Both methods are declared as abstract inside InputStream and OutputStream.

Reading/ Writing File using Streams

Using Byte Streams import java.io.*; class ShowFile { public static void main(String args[]) throws IOException { int i; FileInputStream fin; try { fin = new FileInputStream(args[0]); } catch(FileNotFoundException e) { System.out.println("File Not Found"); return; } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Usage: ShowFile File"); return; } // read characters until EOF is encountered do { i = fin.read(); if(i != -1) System.out.print((char) i); } while(i != -1); fin.close(); }}

Using Byte Streams import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class CopyBytes { public static void main(String[] args) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(“ravi.txt"); out = new FileOutputStream(“Copy.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }

Byte Stream Contd… Note: read() returns an int value. Using a int as a return type allows read() to use -1 to indicate that it has reached the end of the stream.

Closing the Streams Closing a stream when it's no longer needed is very important. It is so important that we have used a finally block to guarantee that both streams will be closed even if an error occurs. This practice helps avoid serious resource leaks. One possible error is that CopyBytes was unable to open one or both files. When that happens, the stream variable corresponding to the file never changes from its initial nullvalue. That's why CopyBytes makes sure that each stream variable contains an object reference before invoking close.

Use of Byte Stream Byte streams should only be used for the most primitive I/O. Since ravi.txt contains character data, the best approach is to use character streams. Byte Stream represents a kind of low-level I/O. So why talk about byte streams? Because all other stream types are built on byte streams.

Byte Stream Classes Stream Class Meaning / Use BufferedInputStream BufferedOutputStream Buffered output stream DataInputStream contains methods for reading the Java standard data types DataOutputStream contains methods for writing the Java standard data types FileInputStream Input stream that reads from a file FileOutputStream Output stream that writes to a file InputStream Abstract class that describes stream input OutputStream Abstract class that describes stream output PrintStream Output stream that contains print() and println( ) PipedInputStream Input Pipe PipedOutputStream Output Pipe Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)

Methods defined by ‘InputStream’ Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)

Methods defined by ‘OutputStream’

FileInputStream

Example

Example (cont.)

Example (cont.)

FileOutputStream Used to write bytes to file. Commonly used constructors: FileOutputStream (String filePath) FileOutputStream (File fileObj) FileOutputStream (String filePath, boolean append) FileOutputStream (File fileObj, boolean append)

FileInputStream Used to read bytes from file. Commonly used constructors: FileInputStream (String filePath) FileInputStream (File fileObj)

FileInputStream

BufferedInputStream BufferedInputStream class allows to wrap any InputStream into buffered stream and achieve performance optimization. Commonly used constructors: BufferedInputStream (InputStream inputstream) BufferedInputStream (InputStream inputstream, int bufSize)

BufferedOutputStream Used to improve performance by reducing no. of times system actually writes data. flush() needs to be called if data is to be written immediately.

DataInputStream & DataOutputStream DataOutputStream & DataInputStream enables to write or read primitive data to or from a stream. They implement DataOutput and DataInput interfaces, respectively; which define methods that convert primitive values to or from sequence of bytes. These steams make it easy to store binary data such as integers or floating-point values in a file.

DataOutputStream It has following constructor: DataOutputStream (OutputStream outputStream) It contains following methods: final void writeDouble (double value) throws IOException final void writeBoolean (boolean value) throws IOException final void writeInt (int value) throws IOException

DataInputStream It has following constructor: DataInputStream (InputStream inputStream) It contains following methods: double readDouble( ) throws IOException boolean readBoolean( ) throws IOException int readInt( ) throws IOException

RandomAccessFile It implements DataInput & DataOutput interfaces, which define basic I/O methods. It is special since it supports positioning requests, i.e. you can position file-pointer within file. It has 2 constructors: RandomAccessFile (File fileObj, String access) throws FileNotFoundException RandomAccessFile (String filename, String access) throws FileNotFoundException access: “r”  file can be read but not written “rw”  file can be read & written “rws”  file opened in read/write mode & every change to file data is immediately written to physical device.

RandomAccessFile It has following methods: void seek (long newPos) throws IOException void setLength (long len) throws IOException Specifies new position in bytes from beginning of file Used to lengthen or shorten a file

RandomAccessFile

Character Stream The Java platform stores character values using Unicode conventions. Character stream I/O automatically translates this internal format to and from the local character set. Character streams are defined by using two class hierarchies. At the top are two abstract classes, Reader and Writer. These abstract classes handle Unicode character streams. Similar to Byte Streams, read() and write() methods are defined in Reader and Writer class.

Character Stream Classes

Methods defined by ‘Reader’ Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)

Methods defined by ‘Writer’

Predefined Streams java.lang package defines a class called System, which encapsulates several aspects of the run-time environment. System contains three predefined stream variables: in, out, and err. These fields are declared as public, static, and final within System. This means that they can be used by any other part of your program and without reference to a specific System object.

Predefined Streams System.out refers to the standard output stream. By default, this is the console. System.in refers to standard input, which is the keyboard by default. System.err refers to the standard error stream, which also is the console by default. However, these streams may be redirected to any compatible I/O device. System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream. These are byte streams, even though they typically are used to read and write characters from and to the console.

BufferedReader (Reader inputReader) Reading Console Input In Java 1.0, the only way to perform console input was to use a byte stream. In Java, console input is accomplished by reading from System.in. To obtain a character-based stream that is attached to the console, wrap System.in in a BufferedReader object. BufferedReader supports a buffered input stream. Its most commonly used constructor is: BufferedReader (Reader inputReader) Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters.

To obtain an InputStreamReader object that is linked to System To obtain an InputStreamReader object that is linked to System.in, use the following constructor: InputStreamReader(InputStream inputStream) Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard: BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); After this statement executes, br is a character-based stream that is linked to the console through System.in.

reading Characters and Strings To read a character from a BufferedReader, use read( ). int read( ) throws IOException Each time read( ) is called, it reads a character from the input stream and returns it as an integer value. It returns –1 when the end of the stream is encountered. It can throw an IOException. To read a string from the keyboard, use readLine( ) that is a member of the BufferedReader class. String readLine( ) throws IOException

reading Characters import java.io.*; class BRRead { public static void main(String args[]) throws IOException { char c; BufferedReader br = new BufferedReader (new InputStreamReader(System.in)); System.out.println("Enter characters, 'q' to quit."); do { c = (char) br.read(); System.out.println(c); } while(c != 'q');

reading String import java.io.*; class BRReadLines { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter lines of text."); System.out.println("Enter 'stop' to quit."); do { str = br.readLine(); System.out.println(str); } while(!str.equals("stop"));

Writing & Reading file

Methods of PrintWriter

Example

Methods of Scanner

Example

Serialization

Serialization Serialization is the process of writing the state of an object to a byte stream. This is useful when we want to save the state of our program to a persistent storage area, such as a file. At a later time, we may restore these objects by using the process of de-serialization. Serialization is also needed to implement Remote Method Invocation (RMI).

An object to be serialized may have references to other objects, which, in turn, have references to still more objects. If we attempt to serialize an object at the top of an object graph, all of the other referenced objects are recursively located and serialized.

Serialization: Interfaces and Classes An overview of the interfaces and classes that support serialization follows: Serializable Only an object that implements the Serializable interface can be saved and restored by the serialization facilities. The Serializable interface defines no members. It is simply used to indicate that a class may be serialized. If a class is serializable, all of its subclasses are also serializable.

void writeExternal (ObjectOutput outStream) throws IOException 2) Externalizable The Externalizable interface is designed for compression or encryption . The Externalizable interface defines two methods: void readExternal (ObjectInput inStream)throws IOException, ClassNotFoundException void writeExternal (ObjectOutput outStream) throws IOException In these methods, inStream is the byte stream from which the object is to be read, and outStream is the byte stream to which the object is to be written.

ObjectOutputStream(OutputStream outStream) throws IOException The ObjectOutput interface extends the DataOutput interface and supports object serialization. It defines the methods several methods. All of these methods will throw an IOExceptionon error conditions. writeObject( )method is called to serialize an object. 4) ObjectOutputStream The ObjectOutputStream class extends the OutputStream class and implements the ObjectOutput interface. It is responsible for writing objects to a stream. Constructor is: ObjectOutputStream(OutputStream outStream) throws IOException The argument outStream is the output stream to which serialized objects will be written.

Serialization Example class MyClass implements Serializable { String s; int i; double d; public MyClass(String s, int i, double d) { this.s = s; this.i = i; this.d = d; } public String toString() return "s=" + s + "; i=" + i + "; d=" + d;

import java.io.*; public class SerializationDemo { public static void main(String args[]) { try { MyClass object1 = new MyClass("Hello", -7, 2.7e10); System.out.println("object1: " + object1); FileOutputStream fos = new FileOutputStream("serial"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(object1); oos.flush(); oos.close(); } catch(IOException e) { System.out.println("Exception during serialization: " + e); System.exit(0);

// Object deserialization try { MyClass object2; FileInputStream fis = new FileInputStream("serial"); ObjectInputStream ois = new ObjectInputStream(fis); object2 = (MyClass)ois.readObject(); ois.close(); System.out.println("object2: " + object2); } catch(Exception e) { System.out.println("Exception during deserialization: " + e); System.exit(0);

Externalization example