CS203 Programming with Data Structures Input and Output California State University, Los Angeles.

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.
1 Streams and Input/Output Files Part I. 2 Introduction So far we have used variables and arrays for storing data inside the programs. This approach poses.
Chapter 19 Binary I/O.
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.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
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.
Files Files are used to store long term data. –Typically referred to as persistent data. –A file is a group of related records. –A list of friends addresses.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L07 (Chapter 18) Binary I/O.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 18 Binary I/O.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Chapter 20 – Streams and Binary Input/Output Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
Java I/O Input: information brought to program from an external source
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 19 Binary I/O.
Chapter 15: Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Use JFileChooser F Text Input.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香.
Chapter 17 Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams  Use JFileChooser F Text Input.
Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Text Input and Output on the Console.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
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.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
Java Input/Output CSE301 University of Sunderland Harry Erwin, PhD Half Lecture.
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.
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.
Copyright(c) Systems and Computer Engineering, Carleton Univeristy, * Object-Oriented Software Development Unit 13 I/O Stream Hierarchy Case.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Binary I/O.
1 Chapter 19 Binary I/O. 2 Motivations F Data stored in a text file – is represented in human-readable form –Text file –Readable –Java source programs.
Chapter 15: Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Parsing Text Files F Random.
Chapter 15: Input and Output
Company Input/Output Stream –. Input/Output Stream Data Program Input Stream Output Stream.
Exception Handling, Reading and Writing in Files, Serialization, Exceptions, Files, Streams, File Readers and Writers, Serializable SoftUni Team Technical.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 13 Java Fundamentals File I/O Serializing an.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Files in Java 1.
1 Chapter 16 Simple Input and Output. 2 Objectives F To discover file properties, delete and rename files using the File class (§16.2). F To understand.
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.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Java IO Exploring the java.io package and living to talk about it.
The Java IO System Different kinds of IO Different kinds of operations
Fundamental of Java Programming
IO in java.
Files and Streams The material in this chapter is not tested on the AP CS exams.
Java Text I/O CS140 Dick Steflik. Reader Abstract super class for character based input Subclasses: – BufferedReader – CharArrayReader – FilterReader.
IO in java.
Chapter 17 Input and Output
Exception Handling, Reading and Writing in Files, Serialization,
Ch14 Files and Streams OBJECTIVES
Chapter 17 Binary I/O.
Object Writing in files
Chapter 17 Binary I/O 1.
Chapter 17 Binary I/O Dr. Clincy - Lecture.
Stream Oriented I/O Computer Programming II Dr. Tim Margush
Chapter 16 Simple Input and Output
Files and Streams in Java
14 Files and Streams.
CS 240 – Advanced Programming Concepts
David Davenport Spring 2005
Presentation transcript:

CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Overview Java IDEs Package Input and output Exception handling

Java IDEs JBuilder Commercial with a scaled-down free version ( JBuilder Foundation ) Eclipse High quality and free Many tools and plug-ins have to be installed separately Netbeans All-in-one package Slow on older computers

IDE Usage Statistics Survey by BZ Research in December 2005 Eclipse: 65.1% JBuilder: 19.2% Netbeans: 17.9%

Package Why do we need it? What does it do? Package and directory

Input and Output Console Scanner System.out GUI File Reader and Writer InputStream and OutputStream Scanner Command line parameters

Understand java.io Package

Stream Types Character streams Textual information Handled by Reader and Writer classes Byte streams Binary information Handled by InputStream and OutputStream classes

Reader Classes BufferedReader ByteArrayReader InputStreamReader FilterReader PipedReader StringReader LineNumberReader FileReader PushbackReader Reader

Writer Classes BufferedWriter ByteArrayWriter OutputStreamWriter FilterWriter PipedWriter StringWriter FileWriter Writer

InputStream Classes FileInputStream PipedInputStream FilterInputStream ByteArrayInputStream SequenceInputStream StringBufferInputStream LineNumberInputStream BufferedInputStream PushbackInputStreamInputStream ObjectInputStream DataInputStream

OutputStream Classes FileOutputStream PipedOutputStream FilterOutputStream ByteArrayOutputStream ObjectOutputStream BufferedOutputStream OutputStream DataOutputStream PrintStream

Basic Streams by Source/Destination Files FileReader/Writer/InputStream/OutputStream Threads PipedReader/Writer/InputStream/OutputStream Memory ByteArrayReader/Writer/InputStream/OutputStream StringReader/Writer StringBufferInputStream General InputStream, InputStreamReader OutputStream, OutputStreamWriter

Basic Stream Operations Basic streams only recognize bytes or characters Operations Read/write a single byte or character Read/write an array of bytes or characters Inconvenient

Wrapper Streams by Function Data conversion DataInputStream/OutputStream Printing PrintStream Buffering BufferedReader/Writer/InputStream/OutputStream Object serialization ObjectInputStream/OutputStream Others

Important Wrapper Streams and Operations DataInputStream and DataOutputStream Read and write primitive types readInt(), readDouble(), … writeInt( int i ), writeDoube( double d ), … BufferedReader readLine() BufferedWriter write( String s )

“Wrapping” Examples // buffered text file read/write BufferedReader br = new BufferedReader( new FileReader(“file”) ); BufferedWriter bw = new BufferedWriter( new FileWriter(“file”) ); // un-buffered binary file read/write DataInputStream di = new DataInputStream( new FileInputStream(“file”) ); DataOutputStream do = new DataOutputStream( new FileOutputStream(“file”) ); // buffered binary file read/write DataInputStream di2 = new DataInputStream( new BufferedInputStream( new FileInputStream() ) ); DataOutputStream do2 = new DataOutputStream( new BufferedOutputStream( new FileOutputStream() ) );

How to Choose from Stream Classes Step 1: Is the data in binary form or textual form? Binary: Input/OutputStream Textual: Reader/Writer Step 2: What’s the data source or data destination? Files, threads, memory, general Step 3: How to process the data? Primitive data types, buffering, …

File Input Example Read from a file in the following format, and sum up all numbers –

Paths Windows Absolute path  c:\path\to\file Relative path  path\to\file Unix Absolute path  /path/to/file Relative path  path/to/file File separators – “/”, “\\”, File.separator

Exception Handling throw and throws try, catch, and finally Exception class getMessage() printStackTrace()

Scanner Class A Java 1.5 feature In java.util package Scanner s = new Scanner(System.in); String param = s.next(); int value = s.nextInt(); s.close(); int sum = 0; Scanner s2 = new Scanner( new File(“test”) ); while( s2.hasNext() ) sum += s2.nextInt(); s2.close()

File Class Not directly related to I/O Check file status Is a file or a directory Exist, readable, writable Name, path, parent Length Perform common file/directory operations Get parent, list children Delete, rename, mkdir

Binary File vs. Text File If we can save data in either binary or text form, which one do we choose? File size Convenience Speed Either way, always use buffering!

Exercise Write a program called Copy that copies a files. Your program should take two arguments from the command line: Source file Destination file E.g. java copy test.txt test2.txt

DataInputStream/ DataOutputStream DataInputStream reads bytes from the stream and converts them into appropriate primitive type values or strings. DataOutputStream converts primitive type values or strings into bytes and output the bytes to the stream.

Using DataInputStream/ DataOutputStream Data streams are used as wrappers on existing input and output streams to filter data in the original stream. They are created using the following constructors: public DataInputStream(InputStream instream) public DataOutputStream(OutputStream outstream) The statements given below create data streams. The first statement creates an input stream for file in.dat; the second statement creates an output stream for file out.dat. DataInputStream infile = new DataInputStream(new FileInputStream("in.dat")); DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat"));

Order and Format CAUTION: You have to read the data in the same order and same format in which they are stored. For example, since names are written in UTF-8 using writeUTF, you must read names using readUTF. If you keep reading data at the end of a stream, an EOFException would occur. So how do you check the end of a file? You can use input.available() to check it. input.available() == 0 indicates that it is the end of a file.

Object I/O ObjectInputStream/ObjectOutputStream enables you to perform I/O for objects in addition for primitive type values and strings.

The Serializable Interface Not all objects can be written to an output stream. Objects that can be written to an object stream is said to be serializable. A serializable object is an instance of the java.io.Serializable interface. So the class of a serializable object must implement Serializable. The Serializable interface is a marker interface. It has no methods, so you don't need to add additional code in your class that implements Serializable. Implementing this interface enables the Java serialization mechanism to automate the process of storing the objects and arrays.

Transient Keyword If an object is an instance of Serializable, but it contains non- serializable instance data fields, can the object be serialized? The answer is no. To enable the object to be serialized, you can use the transient keyword to mark these data fields to tell the JVM to ignore these fields when writing the object to an object stream.

Continued… Consider the following class: public class Foo implements java.io.Serializable { private int v1; private static double v2; private transient A v3 = new A(); } class A { } // A is not serializable When an object of the Foo class is serialized, only variable v1 is serialized. Variable v2 is not serialized because it is a static variable, and variable v3 is not serialized because it is marked transient. If v3 were not marked transient, a java.io.NotSerializableException would occur.

Serializing Arrays An array is serializable if all its elements are serializable. So an entire array can be saved using writeObject into a file and later restored using readObject.

Random Access File All of the streams you have used so far are known as read-only or write-only streams. The external files of these streams are sequential files that cannot be updated without creating a new file. It is often necessary to modify files or to insert new records into files. Java provides the RandomAccessFile class to allow a file to be read from and write to at random locations.

Continued… The problem with the stream model Advantages of RandomAccessFile Deal with both binary and text files Provide both read and write methods seek(long pos) … but we don’t use it often. Why?

File Pointer A random access file consists of a sequence of bytes. There is a special marker called file pointer that is positioned at one of these bytes. A read or write operation takes place at the location of the file pointer. When a file is opened, the file pointer sets at the beginning of the file. When you read or write data to the file, the file pointer moves forward to the next data. For example, if you read an int value using readInt(), the JVM reads four bytes from the file pointer and now the file pointer is four bytes ahead of the previous location.

RandomAccessFile Methods Many methods in RandomAccessFile are the same as those in DataInputStream and DataOutputStream. For example, readInt(), readLong(), writeDouble(), readLine(), writeInt(), and writeLong() can be used in data input stream or data output stream as well as in RandomAccessFile streams.

RandomAccessFile Methods, cont. void seek(long pos) throws IOException; Sets the offset from the beginning of the RandomAccessFile stream to where the next read or write occurs. long getFilePointer() IOException; Returns the current offset, in bytes, from the beginning of the file to where the next read or write occurs.

RandomAccessFile Methods, cont. long length()IOException Returns the length of the file. final void writeChar(int v) throws IOException Writes a character to the file as a two-byte Unicode, with the high byte written first. final void writeChars(String s) throws IOException Writes a string to the file as a sequence of characters.

RandomAccessFile Constructor RandomAccessFile raf = new RandomAccessFile("test.dat", "rw"); //allows read and write RandomAccessFile raf = new RandomAccessFile("test.dat", "r"); //read only

Fixed Length String I/O Random access files are often used to process files of records. For convenience, fixed-length records are used in random access files so that a record can be located easily. A record consists of a fixed number of fields. A field can be a string or a primitive data type. A string in a fixed-length record has a maximum size. If a string is smaller than the maximum size, the rest of the string is padded with blanks.