Chapter - 11 Introduction to File and Streams This chapter includes -  Defining a File  Testing and Checking File Objects  Accessing File Objects.

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

Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
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.
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.
III. Streams. Introduction Often a program needs to bring in information from an external source or to send out information to an external destination.
Standard input, output and error. Lecture Under Construction.
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.
File input and output. Interactive vs. file I/O All of the programs we have seen or written thus far have assumed interaction with a user, who types in.
1 File Output. 2 So far… So far, all of our output has been to System.out  using print(), println(), or printf() All input has been from System.in 
Files and Streams CS 21a Chapter 11 of Horstmann.
Algorithm Programming I/O via Java Streams Bar-Ilan University תשס"ח by Moshe Fresko.
Tirgul 1 Today’s subject - Java reminders and additions: –Inner classes –Packages –I/O streams –Command Line Arguments –Primitive and Reference Data Types.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
פיתוח מונחה עצמים – שפת JAVA קבצים. References קורס "שיטות בהנדסת תוכנה", הפקולטה למדעי המחשב, הטכניון. קורס "מערכות מידע מבוזרות", הפקולטה להנדסת תעשייה.
Java I/O Input: information brought to program from an external source
CSC – Java Programming II Lecture 9 January 30, 2002.
Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class.
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.
1 Chapter 11 – Files and Streams 1 Introduction What are files? –Long-term storage of large amounts of data –Persistent data exists after termination of.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
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.
Program data (instance variables, local variables, and parameters) is transient, because its lifetime ends with the program...if not, before. Sometimes.
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.
Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new.
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
Java Input/Output CSE301 University of Sunderland Harry Erwin, PhD Half Lecture.
Introduction to Programming G50PRO University of Nottingham Unit 11 : Files Input/Ouput Paul Tennent
By Rachel Thompson and Michael Deck.  Java.io- a package for input and output  File I/O  Reads data into and out of the console  Writes and reads.
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.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
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.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Files and Streams CS /02/05 L7: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
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.
Chapter 9 1 Chapter 9 – Part 2 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.
– Advanced Programming P ROGRAMMING IN Lecture 22 Input and Output System.
CIS 234: File Input & Output introduction. Data Storage Is Fundamental computers need to store data to work with it memory (RAM) is fast but transient.
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.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
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.
DEPARTMENT OF COMPUTER SCIENCE N.HARIKA. Contents Overview of I/O Streams Character Streams Byte Streams Using the Streams 2.
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.
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 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.
CS1020 Data Structures and Algorithms I Lecture Note #16 File Processing.
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.
Sequential files creation & writing
OO Design and Programming II I/O: Reading and Writing
File - CIS 1068 Program Design and Abstraction
Lesson 8: More File I/O February 5, 2008
12: The Java I/O System stream model.
I/O Basics.
Programming in Java Files and I/O Streams
File class File myFile=new File(“c:/javaDemo/aa
Comp 212: Intermediate Programming Lecture 30 – Stream and File I/O
Files and Streams in Java
EEC 484/584 Computer Networks
Comp 212: Intermediate Programming Lecture 30 – Stream and File I/O
Presentation transcript:

Chapter - 11 Introduction to File and Streams

This chapter includes -  Defining a File  Testing and Checking File Objects  Accessing File Objects  Modifying File Objects and Files  Understanding Streams  Stream Input/Output  The Classes for Input and Output  FileInputStream  FileOutputStream

 A File object represents a pathname to a physical file or directory on your hard drive  When creating File Objects, you have a choice of three constructors.  The simplest Constructor File myDir= new File ( “F:/jdk1.3/bin”); File sourceFile = new File (“F:/jdk1.3/bin/test.java”);  The second constructor of File class accepts two arguments. File myDir = new File ( “F:/jdk1.3/bin”); File myFile= new File(mydir, “test.java”); Defining a File File Object For a Folder For a Folder

 The third constructor File myFile = new File (“F:/jdk1.3/bin”, “test.java”); The File class provides a whole bunch of methods that you can apply to File objects. Testing and Checking File Objects MethodDescription exists()Returns true if the file or directory referred to by the File object exists and false otherwise. isDirectory()Returns true if the File object refers to a directory and false otherwise. isFile()Returns true if the File object refers to a file and false otherwise.

 Let us try the above methods. import java.io.*; import javax.swing.*; public class TryFile{ public static void main (String args[]){ File myDir=new File ( “F:/jdk1.3/bin”); if (myDir.isDirectory()==true) JOptionPane.showMessageDialog(null,myDir+”is a directory”); else JOptionPane.showMessageDialog(null,myDir+”is not a directory”); canRad()Returns true if you are permitted to read the file referred to by the File object and false otherwise canWrite()Returns true if you are permitted to writethe file referred to by the File object and false otherwise

File myFile=new File (myDir, “test.java”); if (myFile.exists()==true) JOptionPane.showMessageDialog(null, myFile+”does exist”); else JOptionPane.showMessageDialog(null, myFile+”does not exist”); if (myFile.canRead()==true) JOptionPane.showMessageDialog(null, “You can read “+myFile); else JOptionPane.showMessageDialog(null, “You can not read ”+myFile); if (myFile.canWrite()==true) JOptionPane.showMessageDialog(null, “You can write “+myFile); else JOptionPane.showMessageDialog(null, “You can not write ”+myFile);  On my machine, the above example produces the output: F:/jdk1.3/bin is a directory F:/jdk1.3/bin/test.java does exist You can read F:/jdk1.3/bin/test.java You can write F:/jdk1.3/bin/test.java

 We can get information about a File object by using the following methods. Accessing File Objects MethodDescription getName()Returns a String object containing the name of the file without the path. For a File Object representing a directory, just the directory name is returned. getPath()Returns a String object containing the path for the File object including the file or directory name. length()Returns a value of type long that is the length in bytes of the file represented by the current File object. list()If the current File object represents a directory, a String array is returned containing the names of the members of the directory. listFiles()If the current File object represents a directory, it returns an array of File objects corresponding to the files and directories in that directory. listRoots()This static returns an array of File objects, each element in the array corresponding to a root directory in the file system.

 You can list all the root directories on a system with the code: File [] roots =File.listRoots(); for (int i=0;i<roots.length;i++) System.out.println(“Root directory “+i+”: “+roots[i]);  We can list all the files in a directory and when they were last modified with the following program: import java.io.*; import java.util.*; import javax.swing.*; class tryFile2{ public static void main (String args[]) { String name = JOptionPane.showInputDialog(“Directory Name:”); lastModified()Returns a value of type long that represents the time that the directory or file was last modified. This time is the number of milliseconds since midnight on 1 st January 1970 GMT. We can use this value to construct an object of Date class (in java.util package) and represent in date format

File myDir = new File (name); if (myDir.isDirectory()==true) JOptionPane.showMessageDialog(null,myDir+” is a directory”); else JOptionPane.showMessageDialog(null,myDir+” is not a directory”); File contents [ ] = myDir.listFiles(); if(contents != null){ String output=“”; output=output+ “The “+ contents.length+” items in the directory “+myDir.getName() +” are:”; for (int i=0;i<contents.length ; i++){ if (contents[i].isDirectory()) output=output+contents[i]+” is a directory”; else output=output+contents[i]+” is a file”; Date d = new Date( contents[i].lastModified()); output=output+” last modified “ + d); } JOptionPane.showMessageDialog(null, output);

} else JOptionPane.showMessageDialog(null, myDir.getName()+” is not a directory”); System.exit(0); } Modifying File Objects and Files  There are several methods defined in the File class that you can use to change a File objects. Some of heavily used methods are listed below

MethodDescription delete()This will delete the file or directory represented by the current File object and return true if the delete was successful. It won’t delete directories that are not empty. renameTo(File Path) The file represented by the current object will be renamed to the path represented by the File object, passed as an argument to the method. If the operation is successful, true will be returned. Otherwise, false will be returned. mkDir()Creates a directory with the path specified by the current File object. The method returns true if it is successful and false otherwise.  Let us write a program that will take a filename as input and will delete it, then it will take another file name and will rename it to a given name and finally it will take a directory name and will create the directory. import java.io.*; import javax.swing.*;

class filetest{ public static void main (String args[]){ String name=JOptionPane.showInputDialog(“Which file to delete”); File f =new File(name); boolean b = f.delete(); if (b==true) JOptionPane.showMessageDialog(null, f + “is deleted successfully”); else JOptionPane.showMessageDialog(null, f + “ was not deleted”); String name1= JOptionPane.showInputDialog(“Which file to rename”); String name2= JOptionPane.showInputDialog(“New name”); File f1 = new File (name1); File f2 = new File(name2); boolean b2= f1.renameTo(f2); if (b==true) JOptionPane.showMessageDialog(null, “Rename successful”); else JOptionPane.showMessageDialog(null, “ Rename unsuccessful”);

String name3=JOptionPane.showInputDialog(“Directory to create”); File f3 =new File(name3); boolean b3 = f.mkdir(); if (b==true) JOptionPane.showMessageDialog(null, f + “is created successfully”); else JOptionPane.showMessageDialog(null, f + “ was not created”); System.exit(0); }

 Often programs need to bring in information from an external source or send out information to an external destination.  The information can be anywhere: in a file, on disk, somewhere on the network, in memory, or in another program.  Also, it can be of any type: objects, characters, images, or sounds. Streams Stream Input/Output  To bring in information, a program opens a stream on an information source (a file, memory, a socket) and reads the information serially, like this:  Similarly, a program can send information to an external destination by opening a stream to a destination and writing the information out serially, like this:

 No matter where the information is coming from or going to and no matter what type of data is being read or written, the algorithms for reading and writing data is pretty much always the same.  Reading open a stream while more information read information close the stream  Writing open a stream while more information write information close the stream Reading and Writing a Stream

 The java.io package contains a collection of stream classes that support these algorithms for reading and writing. java.io  These classes are divided into two class hierarchies based on the data type (either characters or bytes) on which they operate.  Character Streams  Byte Streams The Classes for Input/Output  Data sink streams read from or write to specialized data sinks such as strings, files, or pipes. Typically, for each reader or input stream intended to read from a specific kind of input source, java.io contains a parallel writer or output stream that can create it. The following table gives java.io 's data sink streams. Using the Data Sink Streams Sink TypeCharacter StreamsByte Streams MemoryCharArrayReader CharArrayWriter ByteArrayInputStream ByteArrayOutputStream StringReader StringWriter StringBufferInputStream

Sink TypeCharacter StreamsByte Streams PipePipeReader PipeWriter PipedInputStream PipedOutputStream FileFileReader FileWriter FileInputStream FileOutputStream How to use File Streams  File streams are perhaps the easiest streams to understand. Simply put, the file streams-- FileReader, FileWriter, FileInputStream, and FileOutputStream --each read or write from a file on the native file system.FileReader FileWriter FileInputStream FileOutputStream

 The following Copy program uses FileReader and FileWriter to copy the contents of a file named farrago.txt into a file called outagain.txt:Copyfarrago.txt import java.io.*; public class Copy { public static void main(String[] args) throws IOException { File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }

 Same Previous program CopyBytes, which uses FileInputStream and FileOutputStream in place of FileReader and FileWriter.CopyBytes import java.io.*; public class CopyBytes { public static void main(String[] args) throws IOException { File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }