15-Jul-15 Simple Java I/O Part I General Principles.

Slides:



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

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.
25-Aug-14 Simple Java I/O Part I General Principles.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
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.
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.
File Handling and Serialization CSIS 3701: Advanced Object Oriented Programming.
© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter Chapter 11 File Input and Output.
Simple Java I/O Part I General Principles. 2 Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Chapter 91 Streams and File I/O Chapter 9. 2 Reminders Project 6 released: due Nov 10:30 pm Project 4 regrades due by midnight tonight Discussion.
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.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
13-Jul-15 Simple Java I/O Part I General Principles.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
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.
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.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
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: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Java I/O Writing and Reading Objects to File Serialization.
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.
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
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.
Chapter 9-Text File I/O. Overview n Text File I/O and Streams n Writing to a file. n Reading from a file. n Parsing and tokenizing. n Random Access n.
3-Jun-16 Simple Java I/O Part I General Principles.
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.
Lecture 5 I/O and Parsing
Chapter 10 Text Files Section 10.2 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
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.
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.
Computer Programming 2 Lecture 10: File streaming (1) Prepared & Presented by: Mahmoud Rafeek Alfarra MINISTRY OF EDUCATION & HIGHER EDUCATION COLLEGE.
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: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as.
Chapter 10: I/O Streams Input Streams Output Streams
Lecture 8: I/O Streams types of I/O streams Chaining Streams
Part I General Principles
CMSC 202 Text File I/O.
I/O Basics.
Part I General Principles
Part I General Principles
Streams and File I/O Chapter 9 Chapter 9.
Streams and File I/O Chapter 14.
Chapter 12 File Input and Output
CSS 161: Fundamentals of Computing
File Input and Output.
Exceptions 10-May-19.
David Davenport Spring 2005
Presentation transcript:

15-Jul-15 Simple Java I/O Part I General Principles

2 Prologue “They say you can hold seven plus or minus two pieces of information in your mind. I can’t remember how to open files in Java. I’ve written chapters on it. I’ve done it a bunch of times, but it’s too many steps. And when I actually analyze it, I realize these are just silly design decisions that they made. Even if they insisted on using the Decorator pattern in java.io, they should have had a convenience constructor for opening files simply. Because we open files all the time, but nobody can remember how. It is too much information to hold in your mind.” —Bruce Eckel,

3 Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for data (sometimes both) An input stream may be associated with the keyboard An input stream or an output stream may be associated with a file Different streams have different characteristics: A file has a definite length, and therefore an end Keyboard input has no specific end

4 How to do I/O import java.io.*; Open the stream Use the stream (read, write, or both) Close the stream

5 Why Java I/O is hard Java I/O is very powerful, with an overwhelming number of options Any given kind of I/O is not particularly difficult The trick is to find your way through the maze of possibilities open use close

6 Opening a stream There is data external to your program that you want to get, or you want to put data somewhere outside your program When you open a stream, you are making a connection to that external place Once the connection is made, you forget about the external place and just use the stream open use close

7 Example of opening a stream A FileReader is a used to connect to a file that will be used for input: FileReader fileReader = new FileReader(fileName); The fileName specifies where the (external) file is to be found You never use fileName again; instead, you use fileReader open use close

8 Using a stream Some streams can be used only for input, others only for output, still others for both Using a stream means doing input from it or output to it But it’s not usually that simple--you need to manipulate the data in some way as it comes in or goes out open use close

9 Example of using a stream int ch; ch = fileReader.read( ); The fileReader.read() method reads one character and returns it as an integer, or -1 if there are no more characters to read The meaning of the integer depends on the file encoding (ASCII, Unicode, other) open use close

10 Manipulating the input data Reading characters as integers isn’t usually what you want to do A BufferedReader will convert integers to characters; it can also read whole lines The constructor for BufferedReader takes a FileReader parameter: BufferedReader bufferedReader = new BufferedReader(fileReader); open use close

11 Reading lines String s; s = bufferedReader.readLine( ); A BufferedReader will return null if there is nothing more to read open use close

12 Closing A stream is an expensive resource There is a limit on the number of streams that you can have open at one time You should not have more than one stream open on the same file You must close a stream before you can open it again Always close your streams! open use close

15-Jul-15 Simple Java I/O Part II LineReader and LineWriter

14 Text files Text (.txt ) files are the simplest kind of files text files can be used by many different programs Formatted text files (such as.doc files) also contain binary formatting information Only programs that “know the secret code” can make sense of formatted text files Compilers, in general, work only with text

15 My LineReader class class LineReader { BufferedReader bufferedReader; LineReader(String fileName) {...} String readLine( ) {...} void close( ) {...} }

16 Basics of the LineReader constructor Create a FileReader for the named file: FileReader fileReader = new FileReader(fileName); Use it as input to a BufferedReader : BufferedReader bufferedReader = new BufferedReader(fileReader); Use the BufferedReader ; but first, we need to catch possible Exceptions

17 The full LineReader constructor LineReader(String fileName) { FileReader fileReader = null; try { fileReader = new FileReader(fileName); } catch (FileNotFoundException e) { System.err.println ("LineReader can't find input file: " + fileName); e.printStackTrace( ); } bufferedReader = new BufferedReader(fileReader); }

18 readLine String readLine( ) { try { return bufferedReader.readLine( ); } catch(IOException e) { e.printStackTrace( ); } return null; }

19 close void close() { try { bufferedReader.close( ); } catch(IOException e) { } }

20 How did I figure that out? I wanted to read lines from a file I found a readLine method in the BufferedReader class The constructor for BufferedReader takes a Reader as an argument An InputStreamReader is a kind of Reader A FileReader is a kind of InputStreamReader

21 The LineWriter class class LineWriter { PrintWriter printWriter; LineWriter(String fileName) {...} void writeLine(String line) {...} void close( ) {...} }

22 The constructor for LineWriter LineWriter(String fileName) { try { printWriter = new PrintWriter( new FileOutputStream(fileName), true); } catch(Exception e) { System.err.println("LineWriter can't " + "use output file: " + fileName); }

23 Flushing the buffer When you put information into a buffered output stream, it goes into a buffer The buffer may not be written out right away If your program crashes, you may not know how far it got before it crashed Flushing the buffer is forcing the information to be written out

24 PrintWriter Buffers are automatically flushed when the program ends normally Usually it is your responsibility to flush buffers if the program does not end normally PrintWriter can do the flushing for you public PrintWriter(OutputStream out, boolean autoFlush)

25 writeLine void writeLine(String line) { printWriter.println(line); }

26 close void close( ) { printWriter.flush( ); try { printWriter.close( ); } catch(Exception e) { } }

15-Jul-15 Simple Java I/O Part III FileDialog s

28 About FileDialog s The FileDialog class displays a window from which the user can select a file The FileDialog window is modal--the application cannot continue until it is closed Only applications, not applets, can use a FileDialog ; only applications can access files Every FileDialog window is associated with a Frame

29 Typical FileDialog window

30 FileDialog constructors FileDialog(Frame f ) Creates a FileDialog attached to Frame f FileDialog(Frame f, String title) Creates a FileDialog attached to Frame f, with the given title FileDialog(Frame f, String title, int type) Creates a FileDialog attached to Frame f, with the given title; the type can be either FileDialog.LOAD or FileDialog.SAVE

31 Useful FileDialog methods I String getDirectory() Returns the selected directory String getFile() Returns the name of the currently selected file, or null if no file is selected int getMode() Returns either FileDialog.LOAD or FileDialog.SAVE, depending on what the dialog is being used for

32 Useful FileDialog methods II void setDirectory(String directory ) Changes the current directory to directory void setFile(String fileName ) Changes the current file to fileName void setMode(int mode ) Sets the mode to either FileDialog.LOAD or FileDialog.SAVE

33 Using a FileDialog Using a FileDialog isn’t difficult, but it is lengthy See my LineReader and LineWriter classes for complete examples

15-Jul-15 Simple Java I/O Part IV Serialization

35 Serialization You can also read and write objects to files Object I/O goes by the awkward name of serialization Serialization in other languages can be very difficult, because objects may contain references to other objects Java makes serialization (almost) easy

36 Conditions for serializability If an object is to be serialized: The class must be declared as public The class must implement Serializable The class must have a no-argument constructor All fields of the class must be serializable: either primitive types or serializable objects

37 Implementing Serializable To “implement” an interface means to define all the methods declared by that interface, but... The Serializable interface does not define any methods! Question: What possible use is there for an interface that does not declare any methods? Answer: Serializable is used as flag to tell Java it needs to do extra work with this class

38 Writing objects to a file ObjectOutputStream objectOut = new ObjectOutputStream( new BufferedOutputStream( new FileOutputStream(fileName))); objectOut.writeObject(serializableObject); objectOut.close( );

39 Reading objects from a file ObjectInputStream objectIn = new ObjectInputStream( new BufferedInputStream( new FileInputStream(fileName))); myObject = (itsType)objectIn.readObject( ); objectIn.close( );

40 What have I left out? Encrypted files, compressed files, files sent over internet connections,... Exceptions! All I/O involves Exceptions! try { statements involving I/O } catch (IOException e) { e.printStackTrace ( ); }

41 The End