Written by Paul Pu All Rights Reservedwww.torontocollege.com 1 Input and Output.

Slides:



Advertisements
Similar presentations
Numbers Treasure Hunt Following each question, click on the answer. If correct, the next page will load with a graphic first – these can be used to check.
Advertisements

CS Network Programming CS 3331 Fall CS 3331 Outline Socket programming Remote method invocation (RMI)
Variations of the Turing Machine
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.
AP STUDY SESSION 2.
1
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.
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 McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 12 File Input and Output Animated Version.
David Burdett May 11, 2004 Package Binding for WS CDL.
CALENDAR.
Break Time Remaining 10:00.
Turing Machines.
PP Test Review Sections 6-1 to 6-6
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Ticket Information Application.
Operating Systems Operating Systems - Winter 2010 Chapter 3 – Input/Output Vrije Universiteit Amsterdam.
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Copyright © 2012, Elsevier Inc. All rights Reserved. 1 Chapter 7 Modeling Structure with Blocks.
Chapter 19 Binary I/O.
Adding Up In Chunks.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
MaK_Full ahead loaded 1 Alarm Page Directory (F11)
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
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.
: 3 00.
5 minutes.
1 hi at no doifpi me be go we of at be do go hi if me no of pi we Inorder Traversal Inorder traversal. n Visit the left subtree. n Visit the node. n Visit.
Types of selection structures
Converting a Fraction to %
Clock will move after 1 minute
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
Physics for Scientists & Engineers, 3rd Edition
Select a time to count down from the clock above
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.
Chapter 10 Ch 1 – Introduction to Computers and Java Streams and File IO 1.
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 Decidability continued…. 2 Theorem: For a recursively enumerable language it is undecidable to determine whether is finite Proof: We will reduce the.
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.
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.
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.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
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.
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 I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
Object Persistence and Object serialization CSNB534 Asma Shakil.
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.
A stream is a sequence of data. A stream is a flowing sequence of characters.
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.
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.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 13 Java Fundamentals File I/O Serializing an.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
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.
Lecture 8: I/O Streams types of I/O streams Chaining Streams
IO in java.
Object Writing in files
Programming in Java Files and I/O Streams
Files and Streams in Java
David Davenport Spring 2005
Presentation transcript:

Written by Paul Pu All Rights Reservedwww.torontocollege.com 1 Input and Output

Written by Paul Pu All Rights Reservedwww.torontocollege.com 2 File Input and Output The File Class The File Class The java.io.File class represent the name of a file or directory that might exist on the host machines file system. For example, you use the File class to find out when a file was last modified or to remove or rename the file. The stream classes are concerned with the contents of the file, whereas the File class is concerned with the storage if the file on a disk. constructors File (String pathname) File(String dir, String subpath); File(File dir, String subpath)

Written by Paul Pu All Rights Reservedwww.torontocollege.com 3 File Input and Output The File Class import java.io.*; public class FileNav{ public static void main(String argv[]){ String[] filenames; File f = new File("."); filenames = f.list(); for(int i=0; i< filenames.length; i++) System.out.println(filenames[i]); }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 4 File Input and Output The File Class Another example is File

Written by Paul Pu All Rights Reservedwww.torontocollege.com 5 File Input and Output The File Class It is important to know that constructing an instance of File does not create a file on the local file system. Remember that the File class can represent a directory as well as a file.

Written by Paul Pu All Rights Reservedwww.torontocollege.com 6 File Input and Output The File Class The program listed below uses some of methods to create a recursive listing of a directory. The application expects the directory to be specified in the command line. import java.io.*; public class FindDirectories { public static void main(String[] args) { // if no arguments provided, start at the parent directory if (args.length == 0) args = new String[] { ".." }; try {

Written by Paul Pu All Rights Reservedwww.torontocollege.com 7 File Input and Output The File Class //Make sure path exists and is a directory File f=new File(path); if(!f.isDirectory()) { System.out.println(path+doesnt exist or not dir); System.exit(0); } //Recursively list contents Lister lister=new Lister(f); lister.setVisible(true); }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 8 File Input and Output The File Class File pathName = new File(args[0]); String[] fileNames = pathName.list(); // enumerate all files in the directory for (int i = 0; i < fileNames.length; i++) { File f = new File(pathName.getPath(), fileNames[i]); // if the file is again a directory, call // the main method recursively if (f.isDirectory()) { System.out.println(f.getCanonicalPath()); main(new String [] { f.getPath() }); }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 9 File Input and Output The File Class catch(IOException e) { e.printStackTrace(); }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 10 File Input and Output The File Class import java.io.*; public class CreateNewFile { public static void main(String args[]){ File f1=new File("IamnewFIle"); System.out.println(f1.getAbsolutePath()); System.out.println("File exists:"+f1.exists()); try { f1.createNewFile(); } catch(IOException e) { } System.out.println("File exists:"+f1.exists()); System.out.println("Is a directory"+f1.isDirectory()); System.out.println("Is a file"+f1.isFile()); System.out.println(" Last modify:"+f1.lastModified());

Written by Paul Pu All Rights Reservedwww.torontocollege.com 11 File Input and Output The File Class f1.createNewFile(); } catch(IOException e) { } System.out.println("File exists:"+f1.exists()); System.out.println("Is a directory"+f1.isDirectory()); System.out.println("Is a file"+f1.isFile()); System.out.println(" Last modify:"+f1.lastModified()); f1.setReadOnly(); File f2=new File("IamnewDIR"); System.out.println(f2.getAbsolutePath()); System.out.println("File exists:"+f2.exists()); f2.mkdir();

Written by Paul Pu All Rights Reservedwww.torontocollege.com 12 File Input and Output The File Class System.out.println("File exists:"+f2.exists()); System.out.println("Is a directory"+f2.isDirectory()); System.out.println("Is a file"+f2.isFile()); System.out.println(" Last modify:"+f2.lastModified()); }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 13 File Input and Output The RandomAccessFile One way to read or modify a file is to use the java.io. RandomAccessFile class. This class presents a model of files that is incompatible with the stream/reader/writer model. With a random-access file, you can seek to a desired position within a file, and then read or write a desired amount of data. The RandomAccessFile class provides methods that support seeking,reading, and writing. Two constructors : RandomAccessFile(String file,String mode) RandomAccessFile(File file,String mode) The mode string should be either r or rw

Written by Paul Pu All Rights Reservedwww.torontocollege.com 14 File Input and Output The RandomAccessFile After a random-access file is constructed, you can seek to any byte position within the file and then read or write. The methods that support seeking are: long getFilePointer() throws IOException This returns the current position within the file, in bytes. Long length() throws IOException: This returns the length of the file, in bytes. Void seek(long position) throws IOException: This sets the current position within the file, in bytes. File start at position 0.

Written by Paul Pu All Rights Reservedwww.torontocollege.com 15 File Input and Output The RandomAccessFile The common methods are: int read() throws IOException: This returns the next byte from the file or -1 if at end of filr. int read(byte dest[]) throws IOException: This attempts to read enough bytes to fill array dest[]. It returns the number of bytes read, or -1 if the file was at end of file int read(byte dest[],int offset,int len) throws IOException This attempts to read len bytes into array dest[], starting at offset. It returns the number of bytes read, or 01 if the file was at end of file. It has same write methods too.

Written by Paul Pu All Rights Reservedwww.torontocollege.com 16 File Input and Output The RandomAccessFile RandomAccessFile has methods for Primitive Types, please check java API.

Written by Paul Pu All Rights Reservedwww.torontocollege.com 17 File Input and Output The RandomAccessFile Example: RandomFileTest.java

Written by Paul Pu All Rights Reservedwww.torontocollege.com 18 File Input and Output Streams, Readers, and Writers Javas stream,reader, and writer classes view input and output as ordered sequences of bytes. A low-level output stream receives bytes and writes bytes to an output device A high-level filter output stream receives general- format data, such as primitives, and writes bytes to a low-level output stream or to another filter output stream A writer is similar to a filter output stream but is specialized for writing Java strings in units of Uncode characters.

Written by Paul Pu All Rights Reservedwww.torontocollege.com 19 File Input and Output Streams, Readers, and Writers A low-level input stream reads bytes from an input device and returns bytes to its caller A high-level filter input stream reads bytes from a low-level input stream, or from another filter input stream, and returns general format data to its caller

Written by Paul Pu All Rights Reservedwww.torontocollege.com 20 File Input and Output Low-Level Streams Low-Level input Streams have methods that read input and return the input as bytes. Low-Level output Streams have methods that are passed bytes, and write thee bytes as output. The FileInputStream and FileOutput Stream classes are excellent examples.

Written by Paul Pu All Rights Reservedwww.torontocollege.com 21 File Input and Output High-Level Streams It is all well to read bytes from input devices and write bytes to output devices. However, more often than not the bytes to be read or written constitute higher-level information such as an int or a string Java supports high-level I/O with high-level streams. A good example of a high-level input stream is the data input stream. DataInputStream(InputStream instrem) DataOutputStream(OutputStream outStream)

Written by Paul Pu All Rights Reservedwww.torontocollege.com 22 File Input and Output High-Level Streams A File bytes int String File Input Stream fis Data Input Stream dis

Written by Paul Pu All Rights Reservedwww.torontocollege.com 23 File Input and Output High-Level Streams A File bytes int String File Input Stream fis Data Input Stream dis Buffered Input Stream bis

Written by Paul Pu All Rights Reservedwww.torontocollege.com 24 File Input and Output High-Level Streams import java.io.*; public class BufIn{ public static void main(String argv[]){ try{ FileInputStream fin = new FileInputStream("BufIn.java"); BufferedInputStream bin = new BufferedInputStream(fin); int ch=0; while((ch=bin.read())> -1){ StringBuffer buf = new StringBuffer(); buf.append((char)ch); System.out.print(buf.toString()); } }catch(IOException e){System.out.println(e.getMessage ());}; }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 25 File Input and Output High-Level Streams //Read the file import java.io.*; public class Dis{ public static void main(String argv[]){ try{ FileInputStream fis= new FileInputStream("fos.dat"); DataInputStream dis = new DataInputStream(fis); System.out.println(dis.readChar()); }catch(IOException e){System.out.println(e.getMessage());} }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 26 File Input and Output High-Level Streams //Write the file import java.io.*; public class Dos{ public static void main(String argv[]){ try{ FileOutputStream fos = new FileOutputStream("fos.dat"); DataOutputStream dos = new DataOutputStream(fos); dos.writeChar('J'); }catch(IOException e){System.out.println(e.getMessage());} }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 27 File Input and Output High-Level Streams import java.io.*; public class BufIn{ public static void main(String argv[]){ try{ FileInputStream fin = new FileInputStream("BufIn.java"); BufferedInputStream bin = new BufferedInputStream(fin); int ch=0; while((ch=bin.read())> -1){ StringBuffer buf = new StringBuffer(); buf.append((char)ch);

Written by Paul Pu All Rights Reservedwww.torontocollege.com 28 File Input and Output High-Level Streams System.out.print(buf.toString()); } }catch(IOException e){System.out.println(e.getMessage());}; }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 29 Reading from standard input // How to read from standard input. import java.io.*; public class Echo { public static void main(String[] args) { DataInputStream in = new DataInputStream( new BufferedInputStream(System.in)); String s; try { while((s = in.readLine()).length() != 0) System.out.println(s); // An empty line terminates the program } catch(IOException e) { e.printStackTrace(); } } ///:~

Written by Paul Pu All Rights Reservedwww.torontocollege.com 30 Readers and Writers Readers and Writers are like input and output streams. What makes readers and writers different is that they are exclusively oriented to Unicode characters. The low-level classes communicate with I/O devices, while the high-level classes communicate with low-level classes. Low-level reader and writer class: FileReader FileWriter PipedReader: These classes provide a mechanism for thread communication StringReader and StringWriter: These classes read and write strings

Written by Paul Pu All Rights Reservedwww.torontocollege.com 31 Readers and Writers The high-level readers and writers all inherit from the Reader or Writer superclass. As with high-level streams, when you construct a hign-level reader or writer you pass in the next- lower object in the chain. The high-level classes: BufferedReader and BufferWriter: These classes have internal buffers so that data can be read or written in large blocks. They are similar to buffered input streams and buffered output streams. PrintWriter: This class is similar to PrintStream, but it writes chars rather than bytes. InputStreamReader and OutputStreamWriter: These classes convert between streams of bytes and sequences of Unicode characters.

Written by Paul Pu All Rights Reservedwww.torontocollege.com 32 Readers and Writers bytes File Reader fr Line Number Reader lnr Chars/strings

Written by Paul Pu All Rights Reservedwww.torontocollege.com 33 Readers and Writers example import java.io.*; public class TestWriter { public static void main(String[] args) { PrintWriter out; String name="Harry Hacker"; double salary=75000; String name1="Tom Avon"; double salary1=80000;

Written by Paul Pu All Rights Reservedwww.torontocollege.com 34 Readers and Writers example try{ out= new PrintWriter(new FileWriter("employee.txt")); out.print(name); out.print(' '); out.println(salary); out.print(name1); out.print(' '); out.println(salary1); out.close(); } catch(IOException e){} }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 35 Readers and Writers example import java.io.*; public class TestReader { public static void main(String[] args) { String line; BufferedReader in; try{ in= new BufferedReader(new FileReader("employee.txt")); while ((line=in.readLine()) !=null){ System.out.println(line); } } catch(IOException e){} }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 36 StringTokenizer and Delimited Text The StreamTokenizer class is used to break any InputStream into a sequence of tokens, which are bits of text delimited by whatever you choose. For example, your tokens could be words, and then they would be delimited by white space and punctuation.

Written by Paul Pu All Rights Reservedwww.torontocollege.com 37 StringTokenizer and Delimited Text public void readStudentFile(String fileName)throws IOException{ Student student; BufferedReader in=new BufferedReader(new FileReader("data.txt")); int c; while((c = in.read()) != -1){

Written by Paul Pu All Rights Reservedwww.torontocollege.com 38 StringTokenizer and Delimited Text String s=in.readLine(); StringTokenizer t=new StringTokenizer(s,"/"); while (t.hasMoreTokens()) { String firstName=t.nextToken(); String lastName=t.nextToken(); String major=t.nextToken(); student=new Student(firstName,lastName,major,Double.parseDouble(t.nextToken()),D ouble.parseDouble(t.nextToken())); putStudent(student); }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 39 StringTokenizer and Delimited Text Example: DataFileTest.java

Written by Paul Pu All Rights Reservedwww.torontocollege.com 40 Object Stream Low-level streams, whether they are connected to disk files or to networks, provide byte-oriented I/O. What is missing is a way to read and write general Java Objects. This functionality is provided by object streams. Write Object: fos=new FileOutputStream(file); os=new ObjectOutputStream(fos); os.writeObject(o); os.close();

Written by Paul Pu All Rights Reservedwww.torontocollege.com 41 Object Stream Read Object: fis=new FileInputStream(file); ois=new ObjectInputStream(fis); o=ois.readObject(); ois.close();

Written by Paul Pu All Rights Reservedwww.torontocollege.com 42 Object Stream import java.io.*; public class Saver { public boolean save(Object o, String file) { boolean status=true; FileOutputStream fos; ObjectOutputStream os; try { fos=new FileOutputStream(file); os=new ObjectOutputStream(fos); os.writeObject(o); os.close(); } catch (Exception ex) { status=false; System.out.println("Save Error" +ex); } return status; }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 43 Object Stream public Object load(String file) { FileInputStream fis; ObjectInputStream ois; Object o=null; try { fis=new FileInputStream(file); ois=new ObjectInputStream(fis); o=ois.readObject(); ois.close(); } catch (Exception ex) { System.out.println("Load Error:"+ex); } return o; }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 44 Object serialization Java 1.1 has added an interesting feature called object serialization that allows you to take any object that implements the Serializable interface and turn it into a sequence of bytes that can later be restored fully into the original object. This is even true across a network, which means that the serialization mechanism automatically compensates for differences in operating systems. That is, you can create an object on a Windows machine, serialize it, and send it across the network to a Unix machine where it will be correctly reconstructed. You dont have to worry about the data representations on the different machines, the byte ordering, or any other details.

Written by Paul Pu All Rights Reservedwww.torontocollege.com 45 Object serialization By itself, object serialization is interesting because it allows you to implement lightweight persistence. Remember that persistence means an objects lifetime is not determined by whether a program is executingthe object lives in between invocations of the program. By taking a serializable object and writing it to disk, then restoring that object when the program is reinvoked, youre able to produce the effect of persistence. The reason its called lightweight is that you cant simply define an object using some kind of persistent keyword and let the system take care of the details (although this might happen in the future). Instead, you must explicitly serialize and de-serialize the objects in your program.

Written by Paul Pu All Rights Reservedwww.torontocollege.com 46 Object serialization Object serialization was added to the language to support two major features. Java 1.1s remote method invocation (RMI) allows objects that live on other machines to behave as if they live on your machine. When sending messages to remote objects, object serialization is necessary to transport the arguments and return values.

Written by Paul Pu All Rights Reservedwww.torontocollege.com 47 Object serialization Object serialization is also necessary for Java Beans, introduced in Java 1.1. When a Bean is used, its state information is generally configured at design time. This state information must be stored and later recovered when the program is started; object serialization performs this task.

Written by Paul Pu All Rights Reservedwww.torontocollege.com 48 Object serialization Serializing an object is quite simple, as long as the object implements the Serializable interface (this interface is just a flag and has no methods). In Java 1.1, many standard library classes have been changed so theyre serializable, including all of the wrappers for the primitive types, all of the container classes, and many others.

Written by Paul Pu All Rights Reservedwww.torontocollege.com 49 Object serialization class Employee implements Serializable { public Employee() {} public Employee(String n, double s, int year, int month, int day) { name = n; salary = s; GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day); // GregorianCalendar uses 0 for January hireDay = calendar.getTime(); }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 50 Object serialization public String getName() { return name; } public double getSalary() { return salary; } public Date getHireDay() { return hireDay; }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 51 Object serialization public void raiseSalary(double byPercent) { double raise = salary * byPercent / 100; salary += raise; } public String toString() { return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]"; } private String name; private double salary; private Date hireDay; }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 52 Object serialization public class Dog { private String name; private int age; public void setName(String name){ this.name=name; } public String getName(){ return name; } public void setAge(int age){ this.age=age; } public int getAge(){ return age; }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 53 Object serialization import java.io.*; public class Distributed_Dog implements Serializable{ private String name; private int age; public void setName(String name){ this.name=name; } public String getName(){ return name; } public void setAge(int age){ this.age=age; } public int getAge(){ return age; }

Written by Paul Pu All Rights Reservedwww.torontocollege.com 54 Object serialization

Written by Paul Pu All Rights Reservedwww.torontocollege.com 55 Object serialization

Written by Paul Pu All Rights Reservedwww.torontocollege.com 56 Display Image Display local image java Test2 logon.jpg

Written by Paul Pu All Rights Reservedwww.torontocollege.com 57 Display Image Display local image java Test3