Introduction to Algorithms and Data Structures



Similar documents
Chapter 10. A stream is an object that enables the flow of data between a program and some I/O device or file. File I/O

D06 PROGRAMMING with JAVA

JAVA.UTIL.SCANNER CLASS

Objectives. Streams and File I/O. Objectives, cont. Outline. I/O Overview. Streams

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Object-Oriented Programming in Java

INPUT AND OUTPUT STREAMS

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

Using Files as Input/Output in Java 5.0 Applications

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Files and input/output streams

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

What is an I/O Stream?

Event-Driven Programming

Input / Output Framework java.io Framework

Introduction to Java

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Programming in Java

CS 1302 Ch 19, Binary I/O

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

Principles of Software Construction: Objects, Design, and Concurrency. Design Case Study: Stream I/O Some answers. Charlie Garrod Jonathan Aldrich

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Creating a Simple, Multithreaded Chat System with Java

AP Computer Science File Input with Scanner

Chapter 2: Elements of Java

13 File Output and Input

JAVA - FILES AND I/O

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

WRITING DATA TO A BINARY FILE

Carron Shankland. Content. String manipula3on in Java The use of files in Java The use of the command line arguments References:

Visit us at

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Stream Classes and File I/O

Course Intro Instructor Intro Java Intro, Continued

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

6.1. Example: A Tip Calculator 6-1

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER

Readings and References. Topic #10: Java Input / Output. "Streams" are the basic I/O objects. Input & Output. Streams. The stream model A-1.

CS 111 Classes I 1. Software Organization View to this point:

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Chapter 3. Input and output. 3.1 The System class

public static void main(string[] args) { System.out.println("hello, world"); } }

Building Java Programs

Building Java Programs

CS 193A. Data files and storage

Explain the relationship between a class and an object. Which is general and which is specific?

D06 PROGRAMMING with JAVA

Quick Introduction to Java

Building a Multi-Threaded Web Server

Introduction to Java. CS 3: Computer Programming in Java

Comp 248 Introduction to Programming

Lecture 5: Java Fundamentals III

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Question R11.3. R11.3 How do you open a file whose name contains a backslash, like c:\temp\output.dat?

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Programming Languages CIS 443

CS506 Web Design and Development Solved Online Quiz No. 01

Basics of Java Programming Input and the Scanner class

Chapter 2 Elementary Programming

Basics of I/O Streams and File I/O

Assignment 4 Solutions

Java Network Programming. The java.net package contains the Socket class. This class speaks TCP (connection-oriented protocol).

Software Development in Java

Install Java Development Kit (JDK) 1.8

Continuous Integration Part 2

AVRO - SERIALIZATION

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

Reading Input From A File

Java from a C perspective. Plan

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. AVRO Tutorial

Division of Informatics, University of Edinburgh

Topic 11 Scanner object, conditional execution

Lesson: All About Sockets

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

COSC 6397 Big Data Analytics. Distributed File Systems (II) Edgar Gabriel Spring HDFS Basics

IMDB Data Set Topics: Parsing Input using Scanner class. Atul Prakash

Programming and Data Structures with Java and JUnit. Rick Mercer

TP N 10 : Gestion des fichiers Langage JAVA

Using Two-Dimensional Arrays

Line-based file processing

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

CS 106 Introduction to Computer Science I

Computer Programming I

java Features Version April 19, 2013 by Thorsten Kracht

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Introduction to Programming

J a v a Quiz (Unit 3, Test 0 Practice)

AP Computer Science Java Mr. Clausen Program 9A, 9B

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

AWS Encryption SDK. Developer Guide

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

Building Java Programs

Transcription:

Introduction to Algorithms and Data Structures Lecture 8 File I/O Streams A stream is an object that allows for the flow of data between a program and some I/O device (or a file). If the flow is into a program it s an input stream. If the flow is out of a program, it s an output stream. System.in and System.out are examples of input and output streams respectively. 1

Text and Binary Files Text files are sequences of characters that can be viewed in a text editor or read by a program. Files whose contents are binary images of information stored in main memory are called binary files. These include the computer s representation of: - numbers - pictures - sound bites - machine instructions The advantage of text files is that they are humanreadable and can be moved easily from computer system to computer system. Writing To A Text File The preferred class for writing to text files is PrintWriter, whose methods include println and print. A PrintWriter object can be created by writing: outputstream = new PrintWrite (new FileOutputStream("stuff.txt")); A FileOutputStream is needed when calling the constructor. It, in turn, needs the name of the file to which output is going to be written. Since opening a file might lead to a FileNotFoundException, it should be done in a try block. 2

Every File Has 2 Names Every file has 2 names: the name by which it is known the operating system of its computer and the name of the stream connect to the file (by which the program knows it). PrintWriter Methods There are three constructors: PrintWriter objectstream = new PrintWriter(OutputStream streamobject); is the standard constructor PrintWriter objectstream = new PrintWriter(new FileOutputStream (FileName)); allows us to construct a file to which it will write. PrintWriter(new FileOutputStream(FileName, true)); which we will use for appending to a file. 3

PrintWriter Methods (continued) public void println(argument) Prints the argument which can be a string, integer, floatingpoint number, or any object for whch a tostring() method exists. public void print(argument) Works like println with the newline at the end. public PrintWriter void printf() Formatted output close() closes the stream flush() flushes the stream, forcing any other data to be written that has been buffered but not yet written. TextFileOutputDemo.java import java.io.printwriter; import java.io.fileoutputstream; import java.io.filenotfoundexception; public class TextFileOutputDemo { public static void main(string[] args) { PrintWriter outputstream = null; try { outputstream = new PrintWriter (new FileOutputStream("stuff.txt")); catch (FileNotFoundException e) { ("\"Error opening the file stuff.txt\"."); System.exit(0); 4

("Writing to file."); outputstream.println("the quick brown fox "); outputstream.println ("jumped over the lazy dogs."); outputstream.close(); ("End of program."); Reading a Text File using Scanner The same Scanner class that we have been using to read input from the keyboard can be used to read from a text file. Although the Scanner has to be declared outside the try block, the constructor should be called inside it. Example Scanner inputstream = null; try { inputstream = new Scanner (new FileInputStream( stuff.txt )); catch(filenotfoundexception e) { 5

Testing for the End of Line If you write Scanner keyb = new Scanner(System.in); int x = keyb.nextint() and there is no more text, (or a non-integer), nextint() will throw a NoSuchElementException You can work around this by using hasnextint()(which return false if there isn t a proper integer there or hasnextline(), which will return false if there is no next line. Some Scanner Constructors There are two constructors in which we can most interested: public Scanner(InputStream streamobject) This can be used to create stream for a file by writing public Scanner (new FileInputStream (filename)); public Scanner(File fileobject) This can be used to create a File object for a file by writing public Scanner(new File(fileName) 6

Some Scanner input Methods Scanner has several methods that can be used to obtain a single data item: - nextint() - nextlong() - nextbyte() - nextshort() - nextdouble() - nextfloat() All these methods will return a single value of the indicated type. If there are no more tokens, they will throw a NoSuchElementException. If the data is not a valid representation of the type, they will throw an InputMismatchException, and if the Scanner is closed, they will throw an IllegalStateException Some Scanner Input Methods Scanner has several methods that can be used to detect that there is valid data waiting as input: - hasnextint() - hasnextlong() - hasnextbyte() - hasnextshort() - hasnextdouble() - hasnextfloat() All these methods will return a true if there is a wellformed string representation of the type of the data item ; false otherwise. If the Scanner is closed, they will throw an IllegalStateException 7

Some Other Scanner Methods Scanner has two methods that can be used to detect that there is valid data waiting as input: - next() - hasnext() - nextline() - nextline() next() and nextline() return the next token and line respectively. hasnext() and hasnextline() return true if there is another token or line respectively; otherwise false. These methods throw the appropriate exceptions. TextFileScannerDemo.java import java.util.scanner; import java.io.fileinputstream; import java.io.filenotfoundexception; public class TextFileScannerDemo { public static void main(string[] args) { ("I will read three nunbers and a line"); ("of text from the file morestuff.txt"); Scanner inputstream = null; try { inputstream = new Scanner (new FileInputStream("morestuff.txt")); 8

catch(filenotfoundexception e) { ("File morestuff.txt was not found."); ("or could not be opened."); System.exit(0); int n1 = inputstream.nextint(); int n2 = inputstream.nextint(); int n3 = inputstream.nextint(); inputstream.nextline(); // Go to the next line String line = inputstream.nextline(); ("The three numbers read from the file are:"); (n1 + ", " + n2 + ", and " + n3); ("The line read from the file is:"); (line); inputstream.close(); 9

HasNextLineDemo.java import java.util.scanner; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.printwriter; import java.io.fileoutputstream; public class HasNextLineDemo { public static void main(string[] args) { Scanner inputstream = null; PrintWriter outputstream = null; try { inputstream = new Scanner(new FileInputStream("original.txt")); outputstream = new PrintWriter(new FileOutputStream("numbered.txt")); catch (FileNotFoundException e) { ("Problem opening files."); System.exit(0); String line = null; int count = 0; while (inputstream.hasnextline()) { line= inputstream.nextline(); count++; outputstream.println(count + " " + line); inputstream.close(); outputstream.close(); 10

HasNextIntDemo.java import java.util.scanner; import java.io.fileinputstream; import java.io.filenotfoundexception; public class HasNextIntDemo { public static void main(string[] args) { Scanner inputstream = null; try { inputstream = new Scanner(new FileInputStream("data.txt")); catch (FileNotFoundException e) { ("File data.txt was not found"); ("or could not be opened."); System.exit(0); int next, sum = 0; while (inputstream.hasnextint()) { next= inputstream.nextint(); sum += next; inputstream.close(); ("The sum of the numbers is " + sum); 11

BufferedReader Class BufferedReader is the class that was used for reading text data before Scanner class was introduced in verion 5.0 of Java. A BufferedReader was used to open a file as shown below: BufferedReader inputstream = new BufferedReader (new FileReader( stuff.txt )); Reading Text Using BufferedReader BufferedReader has methods that are used for input: readline() reads a line of input that is returned as text. If there is no more text, it returns a null reference. read() reads a single character from the input stream that is returned as an integer.. If there is no more text, it returns -1 skip(int n) skips n characters. close() closes the stream s connection to the file. These methods all throw IOException. 12

TextFileInputDemo.java import java.io.bufferedreader; import java.io.filereader; import java.io.filenotfoundexception; import java.io.ioexception; public class TextFileInputDemo { public static void main(string[] args) { try { BufferedReader inputstream = new BufferedReader (new FileReader("morestuff2.txt")); String line = inputstream.readline(); ("The first line read from the file is:"); (line); line= inputstream.readline(); ("The second line read from the file is:"); (line); inputstream.close(); catch(filenotfoundexception e) { ("File morestuff2.txt was not found"); ("or could not be opened."); catch (IOException e) { ("Error reading from morestuff2.txt"); 13

TextEOFDemo.java import java.io.bufferedreader; import java.io.filereader; import java.io.printwriter; import java.io.fileoutputstream; import java.io.filenotfoundexception; import java.io.ioexception; public class TextEOFDemo { public static void main(string[] args) { try { BufferedReader inputstream = new BufferedReader (new FileReader("original.txt")); PrintWriter outputstream = new PrintWriter(new FileOutputStream("numbered.txt")); int count= 0; String line= inputstream.readline(); while (line!= null) { count++; outputstream.println(count + " " + line); line = inputstream.readline(); inputstream.close(); outputstream.close(); catch (FileNotFoundException e) { ("Problem opening file."); catch (IOException e) { ("Error reading from original.txt"); 14

Standard Streams All Java programs are assumed to have at least three open streams: System.in, System.out and System.err (the last one allows for error message and output to be redirects separately). RedirectionDemo.java import java.io.printstream; import java.io.fileoutputstream; import java.io.filenotfoundexception; public class RedirectionDemo { public static void main(string[] args) { PrintStream errstream = null; try { errstream = new PrintStream(new FileOutputStream("errormessage.txt")); catch (FileNotFoundException e) { ("Error opening file with FileOutputSteam."); System.exit(0); 15

System.setErr(errStream); System.err.println("Hello fgom System.err."); System.err.println("Hello from System.out."); System.err.println("Hello again from System.err."); errstream.close(); File Class The File class is a bit like a wrapper class for file names. It also provides us with some methods that can be used to check some basic properties of files, such as whether it exists, does the program have permission to read or write it. Example: File fileobject = new File( data.txt ); if (!fileobject.canread()) ("file data.txt is not readable."); 16

File Class Methods exists() returns true if it exists; false otherwise canread() returns true if the program can read data from the file; false otherwise. canwrite() - returns true if the program can write data from the file; false otherwise. isfile() returns true if the file exists and is a regular file; false otherwise. isdirectory() - returns true if the file exists and is a directory; false otherwise. File Class Methods (continued) length() returns the number of bytes in the file as a long.if it doesn t exist or if it s a directory, the value returned isn t specified. delete() tries to delete the file; returns true if it can, false if it can t. setreadonly() sets the file as read only; returns true if it is can; false if it can t. createnewfile() creates an empty of that name; returns true if it can; false if it can t isfile() returns true if the file exists and is a regular file; false otherwise. isdirectory() - returns true if the file exists and is a directory; false otherwise. 17

File Class Methods (continued) getname() return the simple name (the last part of the path). getpath() returns the abstract (absolute or relative) path name or an empty string if the path name is an empty string.. renameto(newname) renames the file to a name represented by the file object newname; returns true if it is can; false if it can t. createnewfile() creates an empty of that name; returns true if it can; false if it can t mkdir() makes the directory named by the abstract path name. Will not create parent directories; returns true if the file exists and is a regular file; false otherwise. mkdirs() - makes the directory named by the abstract path name. Will necessary but nonexistent create parent directories; returns true if the file exists and is a regular file; false otherwise. FileClassDemo.java import java.util.scanner; import java.io.file; import java.io.printwriter; import java.io.fileoutputstream; import java.io.filenotfoundexception; public class FileClassDemo { public static void main(string[] args) { Scanner keyb= new Scanner(System.in); String line = null; String filename = null; ("I will store a line of text for you."); ("Enter the line of text:"); line = keyb.nextline(); 18

("Enter a file name to hold the line:"); filename = keyb.nextline(); File fileobject = new File(fileName); while (fileobject.exists()) { ("There already is a file named " + filename); ("Enter a different file name:"); filename = keyb.nextline(); fileobject= new File(fileName); PrintWriter outputstream = null; try { outputstream = new PrintWriter(new FileOutputStream(fileName)); catch (FileNotFoundException e) { ("Error opening the file."); System.exit(0); ("writing \"" + line + "\""); ("to the file " + filename); outputstream.println(line); outputstream.close(); ("Writing completed."); 19

Binary Files Text files save data in the same form as they appear on the screen or printed page. This requires the computer to do some conversion when reading and writing them. Binary files save data in their internal form. Strings have their unused bytes saved Numbers are stored in binary form. Classes Used in Writing a Binary File There are two classes of objects used in writing binary files: FileOutputStream stream objects that write data to a file. ObjectOutputStream - objects that take data of a certain type and converting it into a stream of bytes. 20

The writeprimitive() Methods The ObjectOutputStream class has several methods of writeprimitive(di) that allows the programmer to write the data item di of type Primitive into the file. They all throw IOExceptions The methods include: oos.writeint(i)- write integer value i into the binary file dos. oos.writedouble(x) - write double value x into the binary file dos. oos.writechar(c) - write char value c into the binary file dos. BinaryOutputDemo.java import java.io.objectoutputstream; import java.io.fileoutputstream; import java.io.ioexception; public class BinaryOutputDemo { public static void main(string[] args) { try { ObjectOutputStream outputstream = new ObjectOutputStream(new FileOutputStream("numbers.dat")); int i; for (i = 0; i < 5; i++) outputstream.writeint(i); 21

("\"Numbers written to the" + " file numbers.dat\""); outputstream.close(); catch(ioexception e) { ("Problem writing with file output."); Reading a Binary File We do this essentially the same way that we write a binary file. It is very important that we know exactly what the files structure is so we can read it accurately. 22

The readprimitive() Methods The ObjectInputStream class has several methods of readprimitive(di) that allows the programmer to read the data item di of type Primitive from the file. The methods include: ois.readint(i)- read integer value i from the binary file dos. ois.readdouble(x) - read double value x from the binary file dos. ois.readchar(c) read char value c from the binary file dos. BinaryInputDemo.java import java.io.objectinputstream; import java.io.fileinputstream; import java.io.ioexception; import java.io.filenotfoundexception; public class BinaryInputDemo { public static void main(string[] args) { try { ObjectInputStream inputstream = new ObjectInputStream(new FileInputStream("numbers.dat")); ("Reading the file \"numbers.dat\""); int n1 = inputstream.readint(); int n2 = inputstream.readint(); 23

("Numbers read from file:"); (n1); (n2); inputstream.close(); catch(filenotfoundexception e) { ("Cannot find file \"numbers.dat\""); catch(ioexception e) { ("Problem with input from \"numbers.dat\"."); Files And Records Many programming languages and computer systems treat files as a collection of records, where you read and write one record at a time. Java does not have anything exactly analogous to records; we use objects instead. We will create an implementation of the class Serializable so the properties of our objects can be converted into a byte stream and saved in a binary file. 24

SomeClass.java import java.io.serializable; public class SomeClass implements Serializable { private int number; private char letter; public SomeClass() { number = 0; letter = 'A'; public SomeClass(int thenumber, char theletter) { number = thenumber; letter = theletter; public String tostring() { return "Number = " + number + " Letter " + letter; 25

ObjectIODemo.java import java.io.objectoutputstream; import java.io.fileoutputstream; import java.io.objectinputstream; import java.io.fileinputstream; import java.io.ioexception; import java.io.filenotfoundexception; // Demonstrates binaryfile I/O of serializable // class objects public class ObjectIODemo { public static void main(string[] args) { try { ObjectOutputStream outputstream = new ObjectOutputStream(new FileOutputStream("datafile")); SomeClass oneobject = new SomeClass(1, 'A'); SomeClass anotherobject = new SomeClass(42, '2'); outputstream.writeobject(oneobject); outputstream.writeobject(anotherobject); outputstream.close(); ("Data sent fo file."); catch(ioexception e) { ("Problem with file output."); ("Now let\'s reopen the file " + " and display the data."); 26

try { ObjectInputStream inputstream = new ObjectInputStream(new FileInputStream("datafile")); SomeClass readone = (SomeClass) inputstream.readobject(); SomeClass readtwo = (SomeClass) inputstream.readobject(); ("The following were read from the file:"); (readone); (readtwo); catch (FileNotFoundException e) { ("Cannot find datafile."); catch(classnotfoundexception e) { ("Problems with file input."); catch(ioexception e) { ("Problems with file input."); ("End of program."); 27

ArrayIODemo.java import java.io.objectoutputstream; import java.io.fileoutputstream; import java.io.objectinputstream; import java.io.fileinputstream; import java.io.ioexception; import java.io.filenotfoundexception; public class ArrayIODemo { public static void main(string[] args) { SomeClass[] a = new SomeClass[2]; a[0] = new SomeClass(1, 'A'); a[1] = new SomeClass(2, 'B'); try { ObjectOutputStream outputstream = new ObjectOutputStream( new FileOutputStream("arrayfile")); outputstream.writeobject(a); outputstream.close(); catch(ioexception e) { ("Error writing to file."); System.exit(0); ("Array written to file arrayfile."); ("Now let's re-open the " + "file and display the arrow."); 28

SomeClass[] b = null; try { ObjectInputStream inputstream = new ObjectInputStream( new FileInputStream("arrayfile")); b = (SomeClass[])inputStream.readObject(); inputstream.close(); catch (FileNotFoundException e) { ("Cannot find file arrayfile."); System.exit(0); catch (ClassNotFoundException e) { ("Problems with file input."); System.exit(0); catch(ioexception e) { ("Problems with file input."); ("The following array + "elements were read from the file:"); int i; for (i = 0; i < b.length; i++) (b[i]); ("End of program."); 29

Random Access Files We usually read files from the beginning to the end. Files that are always accessed in this fashion as called sequential access files. Sometimes we need to read files from any particular point to which we may need access. These are called random access files. These have two methods that other files do not have: getfilepointer() (which takes us to the current location from which we are reading) and seek() (which moves us to another location in the file). RandomAccessDemo.java import java.io.randomaccessfile; import java.io.ioexception; import java.io.filenotfoundexception; public class RandomAccessDemo { public static void main(string[] args) { try { RandomAccessFile iostream = new RandomAccessFile("bytedata", "rw"); ("Writing 3 bytes to the file bytedata."); iostream.writebyte(1); iostream.writebyte(2); iostream.writebyte(3); ("the length of the file is now = " + iostream.length()); 30

("The file pointer location is " + iostream.getfilepointer()); ("Moving the file pointer to location 1."); iostream.seek(1); byte onebyte = iostream.readbyte(); ("The value at location 1is " + onebyte); onebyte = iostream.readbyte(); ("The value at the next location is " + onebyte); ("Now we can move the file pointer back to "); ("location 1, and change the byte."); iostream.seek(1); iostream.writebyte(9); iostream.seek(1); onebyte = iostream.readbyte(); ("The value at location 1 is now " + onebyte); ("Now we can go to the end of the file"); ("and write a double."); iostream.seek(iostream.length()); iostream.writedouble(41.99); ("the length of the fiule is now = " + iostream.length()); ("Returning to location 3, "); 31

("where we wrote the double."); iostream.seek(3); double onedouble = iostream.readdouble(); ("The double version of location is " + onedouble); iostream.close(); catch(filenotfoundexception e) { ("Problem opening file."); catch (IOException e) { ("Problems with file I/O"); ("End of program."); 32