©SoftMoore ConsultingSlide 1 Appendix G: Java Input/Output.

Slides:



Advertisements
Similar presentations
I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
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.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
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.
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
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.
File I/O in Java CS 311, Winter File Basics Recall that a file is block structured. What does this mean? What happens when an application opens.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
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.
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.
15-Jul-15 Simple Java I/O Part I General Principles.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Java I/O Input: information brought to program from an external source
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.
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.
CIS 270—Application Development II Chapter 14—Files and Streams.
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.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
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.
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 How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
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.
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.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Input/output Input in java is stream based.A stream represents sequence of bytes or characters. Stream provides an abstract view of I/O. Stream can be.
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.
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.
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
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.
Outline  Basic IO  File class  The Stream Zoo  Serialization  Regular Expressions.
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.
1 Exceptions Exception handling – Exception Indication of problem during execution – E.g., divide by zero – Chained exceptions Uses of exception handling.
תוכנה 1 תרגול מס ' 4 שימוש במחלקות קיימות : קלט / פלט (IO)
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.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
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.
Java Input / Output l a modular approach to input/output: - different stream objects are connected/wrapped to handle I/O l a data stream object: a flow.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as.
Generics and file handling Presented by: Abha Kumari Neha Pradip Vhanmane Raj Visa Rashmi Kewlani Suvrat Dixit.
Java IO Exploring the java.io package and living to talk about it.
Keerthi Nelaturu Url: site.uottawa.ca/~knela006
Lecture 8: I/O Streams types of I/O streams Chaining Streams
IO in java.
OO Design and Programming II I/O: Reading and Writing
Lesson 8: More File I/O February 5, 2008
University of Central Florida COP 3330 Object Oriented Programming
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
Programming in Java Files and I/O Streams
Chapter 17 Binary I/O Dr. Clincy - Lecture.
Streams and File I/O Chapter 14.
CSC 143 Java Streams.
Files and Streams in Java
David Davenport Spring 2005
Presentation transcript:

©SoftMoore ConsultingSlide 1 Appendix G: Java Input/Output

©SoftMoore ConsultingSlide 2 The March of Progress (Cay Horstmann) 1980: C printf("%10.2f", x); 1988: C++ cout << setw(10) << setprecision(2) << showpoint << x; 1996: Java java.text.NumberFormat formatter = java.text.NumberFormat.getNumberInstance(); formatter.setMinimumFractionDigits(2); formatter.setMaximumFractionDigits(2); String s = formatter.format(x); for (int i = s.length(); i < 10; i++) System.out.print(' '); System.out.print(s); 2004: Java System.out.printf("%10.2f", x);

The printf() Method Java 5 (2004) added a printf() method to classes PrintStream and PrintWriter. The printf() method in Java is used in a manner similar to the printf() function in C. Each printf() method has at least two arguments –format string, which may contain fixed text and one or more embedded format specifiers –a variable number of arguments whose values are printed according to the format specifiers Example System.out.printf("The answer is %10.2f", x); ©SoftMoore ConsultingSlide 3

©SoftMoore ConsultingSlide 4 Simplified Input: Class Scanner In addition to the printf() method for output, Java 5 also provides the java.util.Scanner class to simplify input. Example: Before Java 5 BufferedReader br = new BufferedReader (new InputStreamReader(System.in); String str = br.readline(); int n = Integer.parseInt(str); Example: Using the Scanner class Scanner s = new Scanner(System.in); int n = s.nextInt();

©SoftMoore ConsultingSlide 5 The File Class Abstract file name Not an actual file! Helps deal with platform differences –methods to manipulate name –rename/delete files –create directories –list directory contents Example File a = new File("/usr/local/bin/foo");

©SoftMoore ConsultingSlide 6 File Names Some information depends on VM Start of path Physical drives Slashes File b = new File("bin/foo"); Example (Windows file names) File c = new File("c:\\windows\\system\\foo.gif"); File d = new File("system\\foo.gif"); (Note the double backslashes!)

©SoftMoore ConsultingSlide 7 Files Relative to Files Can pass a File to the constructor as parent directory File g = new File("/windows/system"); File h = new File(g, "foo.gif"); File i = new File("/windows/system", "foo.gif"); (h and i refer to the same file)

©SoftMoore ConsultingSlide 8 Selected File Methods boolean isDirectory() long lastModified() long length() int compareTo(File) String getName() String getParent() File getParentFile() String getPath() URL toURL() boolean createNewFile() boolean delete() boolean mkdir() boolean renameTo(File) String[] list() File[] listFiles()

©SoftMoore ConsultingSlide 9 Unicode In Java, strings are two-byte Unicode characters Unicode - standard that represents many worldwide characters in two bytes Unicode chars are ASCII –Other “pages” represent other character sets –Different languages –Dingbats –Currency symbols –Mathematical symbols –… and many others

©SoftMoore ConsultingSlide 10 Text Translation Text I/O classes translate native chars to/from Unicode I/O package provides "default mapping" Reading text: I/O classes translate from native to Unicode Writing text: I/O classes translate from Unicode to native Text I/O versus binary I/O –Reader and Writer classes handle text I/O (character translation performed) –InputStream and OutputStream classes handle binary I/O (bytes read/written as is)

©SoftMoore ConsultingSlide 11 Reading and Writing Files To read/write files on a disk: FileInputStream FileOutputStream FileReader FileWriter Provided Constructors class(File) class(String) class(FileDescriptor) class(String, boolean)- [output only]

©SoftMoore ConsultingSlide 12 File Copy Example FileInputStream inFile = new FileInputStream(args[0]); FileOutputStream outFile = new FileOutputStream(args[1]); int byteRead; while((byteRead = inFile.read()) != -1) outFile.write(byteRead); inFile.close(); outFile.close(); Slow implementation! –reading/writing single character at a time –could be really bad over a network connection Can provide simple buffering using byte[] forms of read() and write()

©SoftMoore ConsultingSlide 13 Buffered File Copy FileInputStream inFile = new FileInputStream(args[0]); FileOutputStream outFile = new FileOutputStream(args[1]); byte[] buffer = new byte[1024]; int i; while((i = inFile.read(buffer)) > 0) outFile.write(buffer, 0, i); inFile.close(); outFile.close();

©SoftMoore ConsultingSlide 14 Common I/O Filters I/O package comes with several useful filters buffering to make I/O more efficient encoding primitive types writing the state of entire objects compressing I/O and many more!

©SoftMoore ConsultingSlide 15 Buffering Writing a single byte or character at a time is inefficient Better to write a block of bytes or chars in a single write() java.io includes: BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter You should almost always use these!

©SoftMoore ConsultingSlide 16 Buffering example BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a.bin")); int byte = bis.read(); // reads a block of bytes from // a.bin and returns one byte = bis.read(); // returns next byte bis.close(); // always close outermost!

©SoftMoore ConsultingSlide 17 Reading Lines of Text BufferedReader provides method readLine() –reads all characters up to a “newline” –returns String containing those characters without newline Example BufferedReader br = new BufferedReader(new FileReader(args[0])); String line = null; while((line = br.readLine()) != null) System.out.println(line); br.close(); // always close outermost!

©SoftMoore ConsultingSlide 18 Print Streams PrintStream and PrintWriter provide primitive/object value output System.out and System.err are two predefined instances of PrintStream print() and println() exist for each primitive type and for Object –print() converts its argument to a String, then writes it to its delegate –println() does the same, but follows with the appropriate newline

©SoftMoore ConsultingSlide 19 Flushing and PrintStreams Common use of PrintStream is communicating status to user –Flushing output becomes significant! –When you print output, you need to flush periodically Example PrintStream ps = new PrintStream(new FileOuputStream("foo.txt")); ps.println("Hello!"); ps.flush(); ps.println("How are you?"); ps.flush();

©SoftMoore ConsultingSlide 20 Automatic Flushing Flushing can be easy to forget PrintStream and PrintWriter can “autoflush” –disabled by default. –enabled by passing true to PrintStream or PrintWriter constructor Example PrintStream ps = new PrintStream(new FileOutputStream("foo.txt"), true); ps.println("Hello!"); ps.println("How are you?");

©SoftMoore ConsultingSlide 21 PrintStream and Text Output Note that PrintStream is commonly used for text output! –converts chars to appropriate binary on current platform –output is filtered to convert characters –allows backward compatibility with earlier JDK You should always use PrintWriter for non- System.out text output – it’s more efficient

©SoftMoore ConsultingSlide 22 IO Exceptions and PrintStream PrintStream and PrintWriter do not throw exceptions! System.out and System.err are very heavily used. Exception handling would be painful. PrintStream and PrintWriter catch their own exceptions and set an error flag. If you using these for real output, call checkError() to see if an error has occurred.

©SoftMoore ConsultingSlide 23 Primitive Data Input and Output You can store primitive types via PrintStream Reading these values requires parsing from String values! This is inefficient! Better way: write binary data to a file

©SoftMoore ConsultingSlide 24 Writing Objects Writing object values – object serialization Uses interfaces ObjectInput and ObjectOutput –ObjectInputStream and ObjectOutputStream implement these interfaces Interface Serializable “marks” a class to be written Serialization covered in the Object Serialization course module – no further coverage here

©SoftMoore ConsultingSlide 25 Platform Specifics File systems vary greatly between operating systems –many “common concepts,” but implementations vary significantly –many “unique” features; e.g., UNIX's permission levels –Case-sensitive/insensitive –Characters allowed in file names –Many more I/O Package Helps, But Be Careful! –I/O is the easiest portability killer in applications. –Easy to create applications that work on your platform, but not others. –Always think about portability issues when writing I/O code.

©SoftMoore ConsultingSlide 26 Characters in File Names Each platform defines –valid file name characters –case significant or not –file name length Examples –asterisk ( '*' ) –space ( ' ' ) (some platforms allow, others don't) For maximum portability, restrict file name characters –letters (A-Z and a-z) –numbers (0-9) –start file names with a letter

©SoftMoore ConsultingSlide 27 File Name Case Sensitivity Unix is case sensitive, Windows is not. Other platforms differ as well. Do the following names refer to the same file? littleMissMuffet.txt LittleMissMuffet.txt littleMissMuffet.TXT Recommendations –Use the same case always. –If possible, use all-lower case. –Never intentionally use same name with different cases.

©SoftMoore ConsultingSlide 28 New-Line Characters Where does one “line” of text end and the next begin? Three general patterns: –"\n" the “Unix way” –"\r" the “Macintosh way” –"\r\n" the “DOS/Windows way” This is the easiest trap to fall into with I/O

©SoftMoore ConsultingSlide 29 File Separator in Path Names Which character separates files/directories in path names? –Unix uses “ / ” –Windows uses “ \ ” (which must be represented as “ \\ ” in strings. Recall that File “does the right thing” for slashes. Use system property file.separator for portability.

©SoftMoore ConsultingSlide 30 Path and Class Path Sequence Separator c:;c:\programs [Windows] /usr/local/bin:/bin [UNIX] Note semicolon (';') use in Windows sequence, colon (':') in UNIX sequence These are “path separation characters” (differ between platforms) Use system property path.separator for portability.

©SoftMoore ConsultingSlide 31 Common I/O Exceptions IOException –General I/O exception –Superclass for all other I/O exceptions –Something undesirable happened while performing I/O EOFException –End of stream unexpectedly reached –Normally "end-of-file" is signaled by special value (e.g., 1) FileNotFoundException –File specified in constructor does not exist –Could also mean file being opened in wrong mode, trying to open read-only file for write access

©SoftMoore ConsultingSlide 32 Closing Streams Difficult I/O operation – several subtle problems Where to put close() call? How to deal with exceptions when opening filters? What if filter's close() throws exception?

©SoftMoore ConsultingSlide 33 Correct Approach for Simple File Closing FileReader r = null; try { r = new FileReader("somefile.txt"); // NOTE: No close()! } catch(IOException e) { // message … } finally { if (r != null) try { r.close(); } catch(Exception ignore) {} // couldn't close -- inform user if important }

©SoftMoore ConsultingSlide 34 Using Finally to Copy Files Safely public void copy(File f1, File f2) throws IOException { InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(f1)); out = new BufferedOutputStream(new FileOutputStream(f2)); int x; while ((x = in.read()) != -1) out.write(x); }

©SoftMoore ConsultingSlide 35 Using Finally to Copy Files Safely (continued) finally { if (in != null) try { in.close(); } catch (Exception ignore) {} if (out != null) try { out.close(); } catch (Exception ignore) {} }

New I/O In version 1.4 (2002), Java introduced several “new I/O” capabilities in package java.nio, including –Character set encoders and decoders –Nonblocking I/O –Memory-mapped files –File locking Java 7 contains additional enhancements, including –class Path (enhancement of class File ) –class FileSystem –class WatchService (file change notification) –file attributes ©SoftMoore ConsultingSlide 36