1 CS2200 Software Development Lecture 36: File Processing A. O’Riordan, 2008 (Includes slides by Lewis/Loftus 2205 and K. Brown 2004-07)

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

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.
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.
Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
©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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 12 File Input and Output.
 We can use a combination of the File and FileOutputStream to write a series of bytes to a file.
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.
Files and Streams. Goals To be able to read and write text files To be able to read and write text files To become familiar with the concepts of text.
Files and Streams CS 21a Chapter 11 of Horstmann.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 12 File Input and Output.
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.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Tirgul 1 Today’s subject - Java reminders and additions: –Inner classes –Packages –I/O streams –Command Line Arguments –Primitive and Reference Data Types.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
Two Ways to Store Data in a File Text format Binary format.
Files and Streams 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
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.
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.
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.
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,
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
Winter 2006CISC121 - Prof. McLeod1 Last Time Misc. useful classes in Java: –String –StringTokenizer –Math –System.
Programs & Data Files Notes Data information processed by word processing, spreadsheet or other application programs are stored as data files. Java programs,
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
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.
Chapter 15 Text Processing and File Input/Output Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin,
Two Ways to Store Data in a File  Text format  Binary format.
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.
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
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.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
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.
 Learn about computer files  Use the Path class  Learn about  Streams  Buffers  file organization  Use Java’s IO classes to write to and read from.
1 / 65 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 12 Programming Fundamentals using Java 1.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
OO Design and Programming II I/O: Reading and Writing
Lecture 5 Text File I/O; Parsing.
CMSC 202 Text File I/O.
Lesson 8: More File I/O February 5, 2008
Introduction to programming in java
Strings and File I/O.
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
Streams and File I/O Chapter 14.
Chapter 12 File Input and Output
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Reading and Writing Text Files
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Presentation transcript:

1 CS2200 Software Development Lecture 36: File Processing A. O’Riordan, 2008 (Includes slides by Lewis/Loftus 2205 and K. Brown )

2 Example text File Suppose we have a file (on secondary storage device) containing bank account information called accounts.txt: Henry John The file contains ASCII characters, and can be read/written using text editor. name: Henry account number: balance: €67.32 name: Henry account number: balance: €67.32 name: John account number: balance: €13.25 name: John account number: balance: €13.25

3 I/O Streams An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays. Input stream: Output stream:

4 Types of I/O in Java ●Byte Streams handle I/O of raw binary data. ●Character Streams handle I/O of character data, automatically handling translation to and from the local character set. ●  Buffered Streams optimize input and output by reducing the number of calls to the native API. ●  Scanning and Formatting allows a program to read and write formatted text. ●I/O from the Command Line describes the Standard Streams and the Console object. ●Data Streams handle binary I/O of primitive data type and String values. ●Object Streams handle binary I/O of objects. ●Random access files permit nonsequential, or random, access to a file's contents. ●New I/O - scalable I/O, fast buffered byte and character I/O, and character set conversion  Covered in these notes

import java.awt.*; import javax.swing.JOptionPane; import java.io.*; import java.util.Scanner; public class AccountReader { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader("accounts.txt")); String nameStr = in.nextLine(); String idStr = in.nextLine(); String balanceStr = in.nextLine(); in.close(); JOptionPane.showMessageDialog (null,"The first Account was:" + "\n name: " + nameStr + "\n id: " + idStr + "\n balance: “ + balanceStr, “Message", JOptionPane.PLAIN_MESSAGE); } Example – File input with Scanner

import java.awt.*; import javax.swing.JOptionPane; import java.io.*; import java.util.Scanner; public class AccountReader { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader("accounts.txt")); String nameStr = in.nextLine(); String idStr = in.nextLine(); String balanceStr = in.nextLine(); in.close(); JOptionPane.showMessageDialog (null,"The first Account was:" + "\n name: " + nameStr + "\n id: " + idStr + "\n balance: “ + balanceStr, “Message", JOptionPane.PLAIN_MESSAGE); } Must import the Java supplied packages that define the file-handling (and general user-interface) classes Must import the Java supplied packages that define the file-handling (and general user-interface) classes

import java.awt.*; import javax.swing.JOptionPane; import java.io.*; import java.util.Scanner; public class AccountReader { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader("accounts.txt")); String nameStr = in.nextLine(); String idStr = in.nextLine(); String balanceStr = in.nextLine(); in.close(); JOptionPane.showMessageDialog (null,"The first Account was:" + "\n name: " + nameStr + "\n id: " + idStr + "\n balance: “ + balanceStr, “Message", JOptionPane.PLAIN_MESSAGE); } We are dealing with an external file system, and so things may go wrong – files missing, unexpected end-of-file, etc. We are dealing with an external file system, and so things may go wrong – files missing, unexpected end-of-file, etc.

import java.awt.*; import javax.swing.JOptionPane; import java.io.*; import java.util.Scanner; public class AccountReader { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader("accounts.txt")); String nameStr = in.nextLine(); String idStr = in.nextLine(); String balanceStr = in.nextLine(); in.close(); JOptionPane.showMessageDialog (null,"The first Account was:" + "\n name: " + nameStr + "\n id: " + idStr + "\n balance: “ + balanceStr, “Message", JOptionPane.PLAIN_MESSAGE); } declares a Scanner object, which (ultimately) reads from “accounts.txt” FileReader can take a file name or a File object Alternative: use BufferedReader, see later declares a Scanner object, which (ultimately) reads from “accounts.txt” FileReader can take a file name or a File object Alternative: use BufferedReader, see later

import java.awt.*; import javax.swing.JOptionPane; import java.io.*; import java.util.Scanner; public class AccountReader { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader("accounts.txt")); String nameStr = in.nextLine(); String idStr = in.nextLine(); String balanceStr = in.nextLine(); in.close(); JOptionPane.showMessageDialog (null,"The first Account was:" + "\n name: " + nameStr + "\n id: " + idStr + "\n balance: “ + balanceStr, “Message", JOptionPane.PLAIN_MESSAGE); } nextLine( ) is a method of class Scanner which reads the next line from the file, and returns it as a String nextLine( ) is a method of class Scanner which reads the next line from the file, and returns it as a String

import java.awt.*; import javax.swing.JOptionPane; import java.io.*; import java.util.Scanner; public class AccountReader { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader("accounts.txt")); String nameStr = in.nextLine(); String idStr = in.nextLine(); String balanceStr = in.nextLine(); in.close(); JOptionPane.showMessageDialog (null, "The first Account was:" + "\n name: " + nameStr + "\n id: " + idStr + "\n balance: “ + balanceStr, “Message", JOptionPane.PLAIN_MESSAGE); } Closing the file. If we want to read any more text, we would now have to open the file again, and start reading from the top.

11 The output

12 Reaching the end of the file If we don't know how many lines are in the file, we need to check for this. For example: String inputStr = null; while (in.hasNextLine()) { inputStr = in.nextLine(); JOptionPane(null, "Just read: " + inputStr, “Message”, JOptionPane.PLAIN_MESSAGE); }

13 BufferedReader BufferedReader (in package java.io) is an alternative to Scanner // Uses BufferedReader for file input. public static void readIt(File fromFile) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(fromFile)); //... Loop as long as there are input lines. String line = null; while ((line = reader.readLine()) != null) { System.out.print(line); } reader.close(); } Note: BufferedReader has method readLine(); Scanner has method nextLine()

14 Reading data These procedures will only read data of type String. If we know that the data in the file is meant to be of some other data type, we need to convert the String afterwards. We can use the wrapper classes ( Integer, Double, Boolean, Float, etc.) and their translation methods ( parseInt, parseDouble, parseBoolean, parseFloat, etc.) which take a String as input, and return as output int, double, boolean, float, etc. Warning: to do this conversion successfully, we have to be sure we know what the Strings represent. If we read in a double, and try to convert it to an int, we will get unexpected results. Make sure you know the structure of the files you are reading.

15 Converting Data public class AccountReader { public static void main(String[] args) throws IOException { BufferedReader fileInput = new BufferedReader( new FileReader( new File("accounts.txt"))); String nameStr = fileInput.readLine(); String idStr = fileInput.readLine(); int id = Integer.parseInt(idStr); String balanceStr = fileInput.readLine(); double balance = Double.parseDouble(balanceStr); fileInput.close(); JOptionPane.showMessageDialog (null, "id = " + id + "\nbal = " + balance, “Message", JOptionPane.PLAIN_MESSAGE); }

16 Writing text files import java.io.*; import java.awt.*; public class AccountWriter { public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter("accounts2.txt"))); out.println("David"); out.println("342567"); out.println("31.98"); out.close(); }

17 Appending to a file The example we have just seen creates a new file, and starts writing at the first line. If the file already existed, this would destroy the old version, and we would lose whatever was in there. Sometimes we want to add things to the end of a file that already exists. FileWriter allows us to do that, using a different constructor: FileWriter(File file, boolean append) Constructs a FileWriter object given a File object... new FileWriter(new File("accounts3.txt"), true))...

18 Other methods of PrintWriter println() will print any of the basic data types. print() will print data without taking a new line. flush() will update the output file (BufferedWriter "buffers" its output operations, and so sometimes it will appear not to have written what we asked - flush() corrects this). Note: Using the classes we have seen, there is no way to update a file, apart from adding text to the end. There is no method for adding text to the middle, or changing an arbitrary line in the file.

19 File Class java.io.File is the central class in working with files and directories. Files and directories are both represented by File objects. public static constant: File.separator default path separator (e.g., "/" in Unix, "\" in Windows). Methods (sample) exists()true if file exists isFile()true if this is a normal file isDirectory()true if this is a directory getName()get name of file or directory getPath()get path name The setLastModified() sets the modification date/time for the file. For example, to set the modification time of xanadu.txt to the current time: new File("xanadu.txt").setLastModified(new Date().getTime());

20 Example import java.io.*; import java.util.*; class FileTest { public static void main(String[] args) { if (args.length != 1) { System.err.println("ERROR: must have 1 parameter"); System.exit(1); } try { File f = new File(args[0]); System.out.println("getName() = " + f.getName()); boolean exists = f.exists(); System.out.println("exists() = " + exists); if (!exists) { System.exit(1); } } catch (IOException iox) { System.err.println(iox); }

21 JFileChooser JFileChooser chooser = new JFileChooser("."); int decision = chooser.showOpenDialog(null); File infile = chooser.getSelectedFile(); if (decision == JFileChooser.APPROVE_OPTION && infile != null) { BufferedReader fileInput = new BufferedReader( new FileReader(infile)); decision = chooser.showSaveDialog(null); File outfile = chooser.getSelectedFile(); if (decision == JFileChooser.APPROVE_OPTION && outfile != null) { PrintWriter fileOutput = new PrintWriter( new BufferedWriter( new FileWriter(outfile))); //and now do the reading and writing } path

22 JFileChooser

23 More advanced File IO (not covered) ●files can store data in different formats ●text files contains sequences of ascii characters ●binary files store data in the same format as main memory ●file handling can be by sequential or random access ●a sequential-access file is a continuous stream of data: to go back, you must open again from the beginning ▪text files are sequential access ●a random-access file allows reads and/or writes at any position in the file