Programming in Java Files and I/O Streams

Slides:



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

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.
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.
Chapter 91 Streams and File I/O Chapter 9. 2 Announcements Project 5 due last night Project 6 assigned Exam 2 –Wed., March 21, 7:00 – 8:00 pm, LILY 1105.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L07 (Chapter 18) Binary I/O.
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.
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.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Io package as Java’s basic I/O system continue’d.
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.
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.
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.
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
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.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
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.
A stream is a sequence of data. A stream is a flowing sequence of characters.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
Streams and File I/O Chapter 9. Outline Overview of Streams and File I/O Text-File I/O Using the File Class Basic Binary-File I/O Object I/O with Object.
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.
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.
תוכנה 1 תרגול מס ' 4 שימוש במחלקות קיימות : קלט / פלט (IO)
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.
1 / 65 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 12 Programming Fundamentals using Java 1.
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.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 13 Java Fundamentals File I/O Serializing an.
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.
CSI 3125, Preliminaries, page 1 Files. CSI 3125, Preliminaries, page 2 Reading and Writing Files Java provides a number of classes and methods that allow.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
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.
Chapter 10: I/O Streams Input Streams Output Streams
Fundamental of Java Programming
Sequential files creation & writing
IO in java.
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
OO Design and Programming II I/O: Reading and Writing
CMSC 202 Text File I/O.
Ch14 Files and Streams OBJECTIVES
Object Writing in files
Streams and File I/O.
University of Central Florida COP 3330 Object Oriented Programming
I/O Basics.
Chapter 17 Binary I/O 1.
File.
I/O Streams- Basics Byte Streams and Character Streams
File I/O & collection frame work
Streams and File I/O Chapter 9 Chapter 9.
Објектно орјентисано програмирање
Java Programming Course
Chapter 17 Binary I/O Dr. Clincy - Lecture.
CSS 161: Fundamentals of Computing
Stream Oriented I/O Computer Programming II Dr. Tim Margush
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Files and Streams in Java
Java Basics Introduction to Streams.
OO Java Programming Input Output.
Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream.
Presentation transcript:

Programming in Java Files and I/O Streams 1

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. www.lpuians.com

Files

File Class The File class provides the methods for obtaining the properties of a file/directory and for renaming and deleting a file/directory. An absolute file name (or full name) contains a file name with its complete path and drive letter. For example, c:\book\Welcome.java A relative file name is in relation to the current working directory. The complete directory path for a relative file name is omitted. For example, Welcome.java www.lpuians.com

File Class The File class is a wrapper class for the file name and its directory path. For example, new File("c:\\book") creates a File object for the directory c:\book, new File("c:\\book\\test.dat") creates a File object for the file c:\book\test.dat File class does not contain the methods for reading and writing file contents. www.lpuians.com

Methods and Constructors File(String path_name) Creates a File object for the specified path name. The path name may be a directory or a file. www.lpuians.com

Methods of File Class boolean isDirectory() boolean isHidden() boolean isFile() boolean isDirectory() boolean isHidden() boolean exists() boolean canRead() boolean canWrite() String getName() String getPath() String getAbsolutePath() long lastModified() long length() boolean delete() boolean renameTo(File f) File [] listFiles() www.lpuians.com

Reading and Writing Files In Java, all files are byte-oriented, and Java provides methods to read and write bytes from and to a file. Java allows us to wrap a byte-oriented file stream within a character-based object. We can use Scanner and PrintWriter class to read and write Files. www.lpuians.com

PrinterWriter Class Although using System.out to write to the console is acceptable. The recommended method of writing to the console when using Java is through a PrintWriter stream. PrintWriter is one of the character-based classes. Using a character-based class for console output makes it easier to internationalize your program. PrintWriter(OutputStream outputStream, boolean flushOnNewline) www.lpuians.com

outputStream is an object of type OutputStream. flushOnNewline controls whether Java flushes the output stream every time a println( )method is called. If flushOnNewline is true, flushing automatically takes place. If false, flushing is not automatic. PrintWriter supports the print( ) and println( ) methods for all types including Object. Thus, we can use these methods in the same way as they have been used with System.out. If an argument is not a simple type, the PrintWriter methods call the object’s toString( ) method and then print the result. www.lpuians.com

Using PrintWriter import java.io.*; public class PrintWriterDemo { public static void main(String args[]) PrintWriter pw = new PrintWriter(System.out, true); pw.println(“Using PrintWriter Object"); int i = -7; pw.println(i); double d = 4.5e-7; pw.println(d); } www.lpuians.com

PrintWriter Methods www.lpuians.com

Using Scanner The java.util.Scanner class is used to read strings and primitive values from the console. Scanner breaks the input into tokens delimited by whitespace characters. To read from the keyboard, we create a Scanner as follows: Scanner s = new Scanner(System.in); To read from a file, create a Scanner for a file, as follows: Scanner s = new Scanner(new File(filename)); www.lpuians.com

Scanner Methods www.lpuians.com

I/O Streams

Streams Java implements streams within class hierarchies defined in the java.io package. A stream is an ordered 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. www.lpuians.com

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. www.lpuians.com

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. www.lpuians.com

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. www.lpuians.com

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. www.lpuians.com

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. www.lpuians.com

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. When we call the close(), it clears the buffer by performing the write operation to the destination and then closes the stream. That's why CopyBytes makes sure that each stream variable contains an object reference before invoking close. www.lpuians.com

Binary I/O classes

Binary Input/Output Classes www.lpuians.com

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 www.lpuians.com

Methods defined by ‘InputStream’ www.lpuians.com

Methods defined by ‘OutputStream’ www.lpuians.com

FileInputStream and FileOutputStream FileInputStream and FileOutputStream are stream classes which create byte streams linked to files. FileInputStream(String fileName) throws FileNotFoundException FileInputStream(File f) throws FileNotFoundException FileOutputStream(String fileName) throws FileNotFoundException FileOutputStream(File f) throws FileNotFoundException FileOutputStream(String fileName, boolean append) throws FileNotFoundException FileOutputStream(File f, boolean append) throws FileNotFoundException www.lpuians.com

Reading and Writing Files To read from a file, we can use read( ) that is defined with in FileInputStream. int read( ) throws IOException Each time read() is called, it reads a single byte from the file and returns the byte as an integer value. To write to a file, we can use the write( )method defined by FileOutputStream. void write(int byteval) throws IOException www.lpuians.com

import java.io.*; class CopyFile { public static void main(String args[])throws IOException{ int i; FileInputStream fin=null; FileOutputStream fout=null; fin = new FileInputStream(args[0]); fout = new FileOutputStream(args[1]); try { do { i = fin.read(); if(i != -1) fout.write(i); } while(i != -1); } catch(IOException e) { System.out.println("File Error"); fin.close(); fout.close(); www.lpuians.com

Object Input/Output ObjectInputStream/ObjectOutputStream classes can be used to read/write serializable objects. ObjectInputStream/ObjectOutputStream enables you to perform I/O for objects in addition to primitive type values and strings. ObjectInputStream/ObjectOutputStream contains all the functions of DataInputStream/ DataOutputStream. www.lpuians.com

Constructor and Methods of ObjectInputStream www.lpuians.com

Constructor and Methods of ObjectOutputStream www.lpuians.com

Serialization www.lpuians.com

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). www.lpuians.com

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. www.lpuians.com

Serializable Interface 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. www.lpuians.com

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; www.lpuians.com

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.txt"); 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); www.lpuians.com

// Object deserialization try { MyClass object2; FileInputStream fis = new FileInputStream("serial.txt"); 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); www.lpuians.com

Exercise Write a program which prompts the user to enter the path of the file to be read (f1) and file to be written(f2). Append the content of the file f1 at the end of file f2. www.lpuians.com