Lesson 8: More File I/O February 5, 2008

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
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.
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.
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.
James Tam Simple file handling in Java Simple File Input And Output Types of Java files Simple file output in Java Simple file input in Java.
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.
Java I/O – what does it include? Command line user interface –Initial arguments to main program –System.in and System.out GUI Hardware –Disk drives ->
Java Review 2. The Agenda The following topics were highlighted to me as issues: –File IO (Rem) –Wrappers (Rem) –Interfaces (Rem) –Asymptotic Notation.
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.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Using java’s Scanner class To read from input and from a file. (horstmann ch04 and ch 17)
Java I/O Input: information brought to program from an external source
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
Lecture 7 Exceptions and I/O. Overview of the exception hierarchy A simplified diagram of the exception hierarchy in Java Throwable ErrorException IOException.
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.
Two Ways to Store Data in a File Text format Binary format.
Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) –it acts as.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
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.
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.
I/O in Java Dennis Burford
The Java I/O Classes and Interfaces cont’d
File IO Basics By Dan Fleck Coming up: Data Streams.
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.
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
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.
Lecture 5 I/O and Parsing
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
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.
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.
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.
GENERICS AND FILE HANDLING Saumya Srivastava (977934) Divyangana Pandey (977790) Shubhi Saxena (978108) Arka Das (962969) AHD05/15-16 AJA 21.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
CS 116 Object Oriented Programming II Lecture 11 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
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.
CHAPTER 3 File Output.
Keerthi Nelaturu Url: site.uottawa.ca/~knela006
Lecture 8: I/O Streams types of I/O streams Chaining Streams
Java Text I/O CS140 Dick Steflik. Reader Abstract super class for character based input Subclasses: – BufferedReader – CharArrayReader – FilterReader.
IO in java.
OO Design and Programming II I/O: Reading and Writing
File Input / Output.
Streams & File Input/Output (I/O)
CMSC 202 Text File I/O.
University of Central Florida COP 3330 Object Oriented Programming
Program Input/Output (I/O)
Strings and File I/O.
12: The Java I/O System stream model.
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
File class File myFile=new File(“c:/javaDemo/aa
Streams and File I/O Chapter 14.
CSS 161: Fundamentals of Computing
Reading and Writing Text Files
Unit 6 Working with files. Unit 6 Working with files.
18 File i/o, Parsing.
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Web Design & Development Lecture 8
File Input and Output.
ECE 122 April 14, 2005.
EEC 484/584 Computer Networks
Presentation transcript:

Lesson 8: More File I/O February 5, 2008

Streams and File I/O Types of Streams Reading from and Writing to Streams File Input File class Scanner File Output BufferedWriter w/ FileWriter PrintWriter Will also get our first look at exceptions and how to catch and handle them.

The File Class FileReader can also be instantiated with a File object. The File class is used to represent the path to the file. The name of the class is misleading. The File class is really a path manager where the path can be to a file, or to a directory (a set of files). File inputFile = new File(“inputFile.txt”); BufferedReader br; br = new BufferedReader(new FileReader(inputFile)); String input = br.readLine(); Look at FileReader constructor in the API Look at File class in the API

The File Class (cont.) Call to File class constructor doesn’t create a file with specified filename Creating a file from a File object is done with createNewFile method in File class Example: File myFile; myFile.createNewFile(“input.txt”); Creates new, empty file “input.txt” if it doesn’t already exist and associates it with myFile File object Can use exists method in File class to tell you whether file exists with name specified

Representing Directories with File Class A File object can represent either a file or a directory. Use isDirectory and isFile methods to tell whether the File object represents a directory or a file If File object represents a directory, you can use the list method to get an array of fileames in that directory

Avoiding File System Dependencies Use File objects rather than strings when manipulating file or directory names to avoid system dependencies associated with filenames Use File class equals method to eliminate inconsistencies caused by difference in case and file delimiter used on different systems when comparing file names Example: File myFile(“myFile.txt”); File yourFile(“yourFile.txt”); if(myFile.equals(yourFile) System.out.println(“Files are the same”); Use File class separator instance field instead of / or \ (or other delimiter) when constructing file path names Example: File foo; foo = new File(“Documents” + File.separator + “data.txt”);

Avoiding File System Dependencies (cont.) Use File method getCanonicalFile to return canonical path name for file getCanonicalFile: removes redundant “.” directories provides correct directory separator for system being used provides capitalization preferred by underlying system

Revisiting InputDemo.java import java.io.*; import java.util.*; public class InputDemo { public InputDemo() { } public void readFile() { String studentID, first, last, major; try { FileReader inFile = new FileReader(“students.txt"); BufferedReader br = new BufferedReader(inFile); String input; input = br.readLine(); while (input != null) { Scanner parser = new Scanner(input); studentID = parser.next(); last = parser.next(); first = parser.next(); major = parser.nextLine(); System.out.println(first + ' ' + last + " ID#: " + studentID); } catch (FileNotFoundException ex) { System.out.println("File not found"); catch (IOException ex) { System.out.println("Unable to read from file"); public static void main(String[] args) { InputDemo id = new InputDemo(); id.readFile();

InputDemo.java using File class import java.io.*; import java.util.*; public class InputDemo { public InputDemo() { } public void readFile() { String studentID, first, last, major; try { File inFile = new File(“students.txt”); FileReader inf = new FileReader(inFile); BufferedReader br = new BufferedReader(inf); String input; input = br.readLine(); while (input != null) { Scanner parser = new Scanner(input); studentID = parser.next(); last = parser.next(); first = parser.next(); major = parser.nextLine(); System.out.println(first + ' ' + last + " ID#: " + studentID); } catch (FileNotFoundException ex) { System.out.println("File not found"); catch (IOException ex) { System.out.println("Unable to read from file"); public static void main(String[] args) { InputDemo id = new InputDemo(); id.readFile();

Scanner Scanners are very versatile and can be wrapped around many different streams to process input: Strings Saw this when we parsed the input in the previous example (InputDemo.java) InputStreams System.in - We’ve already seen this one Readers, i.e., FileReader Very similar to the previous example except the Scanner takes the place of the BufferedReader Scanner and BufferedReader provide different methods and functionality. See the JavaDocs. File objects – Scanner can be wrapped directly around File objects. In other words, it takes the place of the FileReader and the BufferedReader.

File Input Using Scanner with a File object Reading from a file with a Scanner File myInputFile = new File(“inputFile.txt”); Scanner inputScanner = new Scanner(myInputFile); String input = inputScanner.nextLine(); Just like with a BufferedReader: Must explicitly handle the possible i/o errors (Exceptions) FileNotFoundException only Close the stream…inputScanner.close() May need to parse input using another Scanner Scanner Example: InputDemoScanner.java

File Output Next, we’ll look at two methods for writing to a file: using a BufferedWriter with the FileWriter class using the PrintWriter class

File Output Using BufferedWriter with FileWriter Instead of sending our output to the console, we’ll write it to a file. Very similar to File Reader and BufferedReader. Writing to a file with a BufferedWriter BufferedWriter bw; bw = new BufferedWriter (new FileWriter(“outputFile.txt”)); outputFile.write(“Here is a string”); outputFile.newLine(); Need to explicitly handle the possible i/o errors (Exceptions) Don’t forget to close the stream…bw.close() BufferedWriter Example: OutputDemo.java Must close the output file in order to flush the data that has been buffered!

File Output Using PrintWriter PrintWriter constructors OutputStream, i.e., FileOutputStream or ObjectOutputStream Writers String, i.e., “outputFile.txt” File Object Writing to a file with PrintWriter (see also PrintStream) File outputFile = new File("outputFile.txt"); PrintWriter output = new PrintWriter(outputFile); output.println("Scanner read following input: " + input); output.printf(…); Need to explicitly handle the possible errors (Exceptions) FileNotFoundException only Don’t forget to close the stream…output.close() PrintWriter Example: OutputDemoPrint.java PrintStream javadocs: All characters printed by a PrintStream are converted into bytes using the platform's default character encoding. The PrintWriter class should be used in situations that require writing characters rather than bytes. Neither PrintStream nor PrintWriter throw the IOExceptions therefore they don’t need to be caught. See PrintStream javadoc Must flush output buffers

Punch Line Pick a way to read from and write to a file and stick with it for now. My recommendation File input: use the Scanner with a File object File output: use the PrintWriter with a File object