CS1101: Programming Methodology

Slides:



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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 12 File Input and Output Animated Version.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12 File Input and Output.
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.
King Saud University College of Computer and Information Sciences Department of Computer Science Dr. S. HAMMAMI Chapter 3 File Input/Output Chapter 3 File.
© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter Chapter 11 File Input and Output.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 12 File Input and Output.
File Input and Output Recitation 04/03/2009 CS 180 Department of Computer Science, Purdue University.
 We can use a combination of the File and FileOutputStream to write a series of bytes to a file.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12 File Input and Output.
1 CS2200 Software Development Lecture 36: File Processing A. O’Riordan, 2008 (Includes slides by Lewis/Loftus 2205 and K. Brown )
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L07 (Chapter 18) Binary I/O.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 12 File Input and Output.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
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.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Chapter 20 – Streams and Binary Input/Output Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
Java I/O Input: information brought to program from an external source
CS1101: Programming Methodology Aaron Tan.
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.
Object Input/Output. Object I/O  To write objects to a file, we use ObjectOutputStream  To read objects from a file we use ObjectInputStream  Lets.
Working with files By the end of this lecture you should be able to: explain the principles of input and output and identify a number of different input.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Files and Streams. Midterm exam Time: Wednesday, October 31, 2007 Format: Multiple choices (about 15 to 20 questions) Determine the results of the code.
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,
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
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.
Programs & Data Files Notes Data information processed by word processing, spreadsheet or other application programs are stored as data files. Java programs,
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Selection sort and Merge sort File input/output. HW 2 – Section 02 Avg = 96/100.
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.
Two Ways to Store Data in a File  Text format  Binary format.
© Amir Kirsh Files and Streams in Java Written by Amir Kirsh.
CHAPTER 15 STREAMS. CHAPTER GOALS To be able to read and write files To become familiar with the concepts of text and binary files To be able to read.
CIS 270—App Dev II Big Java Chapter 19 Files and Streams.
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.
Programs & Data Files Notes Data information processed by word processing, spreadsheet or other application programs are stored as data files. Java.
File Input & Output1 Streams & File I/O. Introduction (1) The Java platform includes a number of packages that are concerned with the movement of data.
Recitation File I/O. File I/O File inFile = new File("data.txt"); File inFile = new File (“/Users/sunil/test.txt");
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
Introduction to OOP with Java 4th Ed, C. Thomas Wu
OO Design and Programming II I/O: Reading and Writing
File I/O CLI: File Input CLI: File Output GUI: File Chooser
CMSC 202 Text File I/O.
Introduction to programming in java
Object Writing in files
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
Chapter 17 Binary I/O 1.
Computer Programming Methodology File Input
Accessing Files in Java
Programming in Java Files and I/O Streams
Streams and File I/O Chapter 9 Chapter 9.
Chapter 17 Binary I/O Dr. Clincy - Lecture.
Chapter 12 File Input and Output
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
CS 240 – Advanced Programming Concepts
David Davenport Spring 2005
Presentation transcript:

CS1101: Programming Methodology http://www.comp.nus.edu.sg/~cs1101x/ CS1101X Programming Methodology CS1101: Programming Methodology http://www.comp.nus.edu.sg/~cs1101x/

Lecture 12: File Input and Output CS1101X Programming Methodology Lecture 12: File Input and Output After you have read and studied this chapter, you should be able to UNIX file redirection Include a JFileChooser object in your program to let the user specify a file. Write bytes to a file and read them back from the file, using FileOutputStream and FileInputStream. Write values of primitive data types to a file and read them back from the file, using DataOutputStream and DataInputStream. Write text data to a file and read them back from the file, using PrintWriter and BufferedReader Read a text file using Scanner Write objects to a file and read them back from the file, using ObjectOutputStream and ObjectInputStream CS1101X: Lecture #12 Acknowledgement: Thomas Wu.

UNIX File Input Redirection CS1101X Programming Methodology UNIX File Input Redirection <:To redirect input from a file $ java MyProgram < inputFile The text file inputFile contains the input data. $ java MySum Enter 3 integers: 4 2 3 Sum = 9 $ cat sum.in 4 2 3 $ java MySum < sum.in Enter 3 integers: Sum = 9 CS1101X: Lecture #12

CS1101X Programming Methodology Example MySum.java import java.util.*; class MySum { public static void main (String[] args) { Scanner scanner = new Scanner(System.in); System.out.print( "Enter 3 integers: " ); int a = scanner.nextInt(); int b = scanner.nextInt(); int c = scanner.nextInt(); int sum = a + b + c; System.out.println( "Sum = " + sum); } CS1101X: Lecture #12

UNIX File Output Redirection CS1101X Programming Methodology UNIX File Output Redirection >:To redirect output to a file (>>: to append to a file) $ java MyProgram > outputFile The text file outputFile contains the output data. $ java MySum Enter 3 integers: 4 2 3 Sum = 9 $ java MySum > sum.out 4 2 3 $ cat sum.out Enter 3 integers: Sum = 9 CS1101X: Lecture #12

Combining Input and Output Redirection CS1101X Programming Methodology Combining Input and Output Redirection You may use input and output redirections together. $ java MyProgram < inputFile > outputFile $ java MySum Enter 3 integers: 4 2 3 Sum = 9 $ java MySum < sum.in > sum.out CS1101X: Lecture #12

CS1101X Programming Methodology The File Class To operate on a file, we must first create a File object (from java.io). Opens the file sample.dat in the current directory. File inFile = new File(“sample.dat”); File inFile = new File (“C:/SamplePrograms/test.dat”); Opens the file test.dat in the directory C:\SamplePrograms using the generic file separator / and providing the full pathname. CS1101X: Lecture #12

CS1101X Programming Methodology Some File Methods if ( inFile.exists( ) ) { To see if inFile is associated to a real file correctly. if ( inFile.isFile() ) { To see if inFile is associated to a file or not. If false, it is a directory. File directory = new File("C:/JavaPrograms/Ch12"); String filename[] = directory.list(); for (int i = 0; i < filename.length; i++) { System.out.println(filename[i]); } List the name of all files in the directory C:\JavaProjects\Ch12 CS1101X: Lecture #12

The JFileChooser Class CS1101X Programming Methodology The JFileChooser Class A javax.swing.JFileChooser object allows the user to select a file. JFileChooser chooser = new JFileChooser( ); chooser.showOpenDialog(null); To start the listing from a specific directory: JFileChooser chooser = new JFileChooser("D:/JavaPrograms/Ch12"); chooser.showOpenDialog(null); CS1101X: Lecture #12

Getting Info from JFileChooser CS1101X Programming Methodology Getting Info from JFileChooser int status = chooser.showOpenDialog(null); if (status == JFileChooser.APPROVE_OPTION) { JOptionPane.showMessageDialog(null, "Open is clicked"); } else { //== JFileChooser.CANCEL_OPTION JOptionPane.showMessageDialog(null, "Cancel is clicked"); } File selectedFile = chooser.getSelectedFile(); File currentDirectory = chooser.getCurrentDirectory(); CS1101X: Lecture #12

CS1101X Programming Methodology Applying a File Filter A file filter may be used to restrict the listing in JFileChooser to only those files/directories that meet the designated filtering criteria. To apply a file, we define a subclass of the javax.swing.filechooser.FileFilter class and provide the accept and getDescription methods. public boolean accept(File file) public String getDescription( ) See the JavaFilter class that restricts the listing to directories and Java source files. CS1101X: Lecture #12

CS1101X Programming Methodology Low-Level File I/O To read data from or write data to a file, we must create one of the Java stream objects and attach it to the file. A stream is a sequence of data items, usually 8-bit bytes. Java has two types of streams: an input stream and an output stream. An input stream has a source form which the data items come, and an output stream has a destination to which the data items are going. CS1101X: Lecture #12

Streams for Low-Level File I/O CS1101X Programming Methodology Streams for Low-Level File I/O FileOutputStream and FileInputStream are two stream objects that facilitate file access. FileOutputStream allows us to output a sequence of bytes; values of data type byte. FileInputStream allows us to read in an array of bytes. CS1101X: Lecture #12

Sample: Low-Level File Output CS1101X Programming Methodology Sample: Low-Level File Output //set up file and stream File outFile = new File("sample1.data"); FileOutputStream outStream = new FileOutputStream( outFile ); //data to save byte[] byteArray = {10, 20, 30, 40, 50, 60, 70, 80}; //write data to the stream outStream.write( byteArray ); //output done, so close the stream outStream.close(); CS1101X: Lecture #12

Sample: Low-Level File Input CS1101X Programming Methodology Sample: Low-Level File Input //set up file and stream File inFile = new File("sample1.data"); FileInputStream inStream = new FileInputStream(inFile); //set up an array to read data in int fileSize = (int)inFile.length(); byte[] byteArray = new byte[fileSize]; //read data in and display them inStream.read(byteArray); for (int i = 0; i < fileSize; i++) { System.out.println(byteArray[i]); } //input done, so close the stream inStream.close(); CS1101X: Lecture #12

Streams for High-Level File I/O CS1101X Programming Methodology Streams for High-Level File I/O FileOutputStream and DataOutputStream are used to output primitive data values FileInputStream and DataInputStream are used to input primitive data values To read the data back correctly, we must know the order of the data stored and their data types CS1101X: Lecture #12

Setting up DataOutputStream CS1101X Programming Methodology Setting up DataOutputStream A standard sequence to set up a DataOutputStream object: File outFile = new File( "sample2.data" ); FileOutputStream outFileStream = new FileOutputStream(outFile); DataOutputStream outDataStream = new DataOutputSteam(outFileStream); CS1101X: Lecture #12

CS1101X Programming Methodology Sample Output import java.io.*; class Ch12TestDataOutputStream { public static void main (String[] args) throws IOException { . . . //set up outDataStream //write values of primitive data types to the stream outDataStream.writeInt(987654321); outDataStream.writeLong(11111111L); outDataStream.writeFloat(22222222F); outDataStream.writeDouble(3333333D); outDataStream.writeChar('A'); outDataStream.writeBoolean(true); //output done, so close the stream outDataStream.close(); } CS1101X: Lecture #12

Setting up DataInputStream CS1101X Programming Methodology Setting up DataInputStream A standard sequence to set up a DataInputStream object: File inFile = new File( "sample2.data" ); FileOutputStream inFileStream = new FileOutputStream(inFile); DataOutputStream inDataStream = new DataOutputSteam(inFileStream); CS1101X: Lecture #12

CS1101X Programming Methodology Sample Input import java.io.*; class Ch12TestDataInputStream { public static void main (String[] args) throws IOException { . . . //set up inDataStream //read values back from the stream and display them System.out.println(inDataStream.readInt()); System.out.println(inDataStream.readLong()); System.out.println(inDataStream.readFloat()); System.out.println(inDataStream.readDouble()); System.out.println(inDataStream.readChar()); System.out.println(inDataStream.readBoolean()); //input done, so close the stream inDataStream.close(); } CS1101X: Lecture #12

Reading Data Back in Right Order CS1101X Programming Methodology Reading Data Back in Right Order The order of write and read operations must match in order to read the stored primitive data back correctly. outStream.writeInteger(…); outStream.writeLong(…); outStream.writeChar(…); outStream.writeBoolean(…); <integer> <long> <char> <boolean> inStream.readInteger(…); inStream.readLong(…); inStream.readChar(…); inStream.readBoolean(…); CS1101X: Lecture #12

Textfile Input and Output CS1101X Programming Methodology Textfile Input and Output Instead of storing primitive data values as binary data in a file, we can convert and store them as a string data. This allows us to view the file content using any text editor To output data as a string to file, we use a PrintWriter object To input data from a textfile, we use FileReader and BufferedReader classes From Java 5.0 (SDK 1.5), we can also use the Scanner class for inputting textfiles CS1101X: Lecture #12

Sample Textfile Output import java.io.*; class Ch12TestPrintWriter { public static void main (String[] args) throws IOException { //set up file and stream File outFile = new File("sample3.data"); FileOutputStream outFileStream = new FileOutputStream(outFile); PrintWriter outStream = new PrintWriter(outFileStream); //write values of primitive data types to the stream outStream.println(987654321); outStream.println("Hello, world."); outStream.println(true); //output done, so close the stream outStream.close(); } CS1101X: Lecture #12

Sample Textfile Input import java.io.*; class Ch12TestBufferedReader { public static void main (String[] args) throws IOException { //set up file and stream File inFile = new File("sample3.data"); FileReader fileReader = new FileReader(inFile); BufferedReader bufReader = new BufferedReader(fileReader); String str; str = bufReader.readLine(); int i = Integer.parseInt(str); //similar process for other data types bufReader.close(); } CS1101X: Lecture #12

Sample Textfile Input with Scanner import java.io.*; class Ch12TestScanner { public static void main (String[] args) throws IOException { //open the Scanner Scanner scanner = new Scanner(new File("sample3.data")); //get integer int i = scanner.nextInt(); //similar process for other data types scanner.close(); } CS1101X: Lecture #12

Object File I/O It is possible to store objects just as easily as you store primitive data values. We use ObjectOutputStream and ObjectInputStream to save to and load objects from a file. To save objects from a given class, the class declaration must include the phrase implements Serializable. For example, class Person implements Serializable { . . . } CS1101X: Lecture #12

Saving Objects File outFile = new File("objects.data"); FileOutputStream outFileStream = new FileOutputStream(outFile); ObjectOutputStream outObjectStream = new ObjectOutputStream(outFileStream); Person person = new Person("Mr. Espresso", 20, 'M'); outObjectStream.writeObject( person ); account1 = new Account(); bank1 = new Bank(); outObjectStream.writeObject( account1 ); outObjectStream.writeObject( bank1 ); Could save objects from the different classes. CS1101X: Lecture #12

Reading Objects File inFile = new File("objects.data"); FileInputStream inFileStream = new FileInputStream(inFile); ObjectInputStream inObjectStream = new ObjectInputStream(inFileStream); Person person = (Person) inObjectStream.readObject( ); Must type cast to the correct object type. Account account1 = (Account) inObjectStream.readObject( ); Bank bank1 = (Bank) inObjectStream.readObject( ); Must read in the correct order. CS1101X: Lecture #12

Saving and Loading Arrays Instead of processing array elements individually, it is possible to save and load the whole array at once. Person[] people = new Person[ N ]; //assume N already has a value //build the people array . . . //save the array outObjectStream.writeObject ( people ); //read the array Person[ ] people = (Person[]) inObjectStream.readObject( ); CS1101X: Lecture #12

End of Lecture #12 CS1101X: Lecture #12