Part I General Principles

Slides:



Advertisements
Similar presentations
I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Advertisements

25-Aug-14 Simple Java I/O Part I General Principles.
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.
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.
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.
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.
21-Jun-15 Simple Text I/O. java.util.Scanner Java finally has a fairly simple way to read input First, you must create a Scanner object To read from the.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 12 File Input and Output.
26-Jun-15 Simple Text I/O. java.util.Scanner Java finally has a fairly simple way to read input First, you must create a Scanner object To read from the.
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.
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.
15-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.
CSC – Java Programming II Lecture 9 January 30, 2002.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
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.
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.
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
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.
Building java programs chapter 6
3-Jun-16 Simple Java I/O Part I General Principles.
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.
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.
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.
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 and Output. Java Input  Input is any information needed by your program to complete its execution  So far we have been using InputBox for.
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.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Lecture 4 CS140 Dick Steflik. Reading Keyboard Input Import java.util.Scanner – A simple text scanner which can parse primitive types and strings using.
java.io supports console and file I/O
Lecture 8: I/O Streams types of I/O streams Chaining Streams
Basic Text File Input/Output
File - CIS 1068 Program Design and Abstraction
File I/O CLI: File Input CLI: File Output GUI: File Chooser
Streams & File Input/Output (I/O)
CMSC 202 Text File I/O.
Introduction to programming in java
Objectives You should be able to describe: Interactive Keyboard Input
Streams and File I/O.
University of Central Florida COP 3330 Object Oriented Programming
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
Part I General Principles
Part I General Principles
I/O Streams- Basics Byte Streams and Character Streams
CSS161: Fundamentals of Computing
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
Introduction to Primitives
Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream.
Presentation transcript:

Part I General Principles Simple Java I/O Part I General Principles 16-Apr-18

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

open use close 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

Types of Streams There are 2 kinds of streams byte streams character streams

Character Streams Character streams create text files. These are files designed to be read with a text editor. Java automatically converts its internal unicode characters to the local machine representation (ASCII in our case).

Byte Streams Byte streams create binary files. A binary file essentially contains the memory image of the data. That is, it stores bits as they are in memory. Binary files are faster to read and write because no translation need take place. Binary files, however, cannot be read with a text editor.

Classes Java has 6 classes to support stream I/O File: An object of this class is either a file or a directory. OutputStream: base class for byte output streams InputStream: base class for byte input streams

Writer: base class for character output streams. Reader: base class for character input streams. RandomAccessFile: provides support for random access to a file. Note that the classes InputStream, OutputStream, Reader, and Writer are abstract classes. Three stream objects are automatically created for every application: System.in, System.out, and System.err.

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

open use close 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

Output to files Printing into an output file, general syntax: PrintStream: An object in the java.io package that lets you print output to a file. System.out is also a PrintStream. Any methods you have used on System.out (such as print, println) will work on every PrintStream. Printing into an output file, general syntax: PrintStream <name> = new PrintStream(new File("<file name>")); If the given file does not exist, it is created. If the given file already exists, it is overwritten.

Printing to files, example PrintStream output = new PrintStream(new File("output.txt")); output.println("Hello, file!"); output.println("This is a second line of output."); You can use similar ideas about prompting for file names here.

Closing A stream is an expensive resource open use close 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! Java will normally close your streams for you when your program ends, but it isn’t good style to depend on this

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

Part IV Scanner and printf Simple Java I/O Part IV Scanner and printf 16-Apr-18

java.util.Scanner Java finally has a fairly simple way to read input First, you must create a Scanner object To read from the keyboard (System.in), do: Scanner scanner = new Scanner(System.in); To read from a file, do: File myFile = new File("myFileName.txt"); Scanner scanner = new Scanner(myFile); You have to be prepared to handle a FileNotFound exception You can even “read” from a String: Scanner scanner = new Scanner(myString); This can be handy for parsing a string

Using the Scanner You can read a line at a time First, you should make sure there is something to scan scanner.hasNext()  boolean You wouldn’t use this when reading from the keyboard You can read a line at a time scanner.nextLine()  String Or, you can read one “token” at a time A token is any sequence of nonwhitespace characters scanner.next ()  String You must be prepared to deal with exceptions Eclipse will tell you what you need to do nextLine and next return Strings, which you can convert to numbers or other types if you like There are also methods to check for and return primitives directly

Scanning for primitives You can read in and convert text to primitives: boolean b = sc.nextBoolean(); byte by = sc.nextByte(); short sh = sc.nextShort(); int i = sc.nextInt(); long l = sc.nextLong(); float f = sc.nextFloat(); double d = sc.nextDouble(); And test if you have something to read: hasNextBoolean() hasNextByte() hasNextShort() hasNextInt() hasNextLong() hasNextFloat() hasNextDouble()

Formatted output Java 5 has a printf method, similar to that of C Each format code is % width code Some format codes are s for strings, d for integers, f for floating point numbers Example: double pi = Math.PI; System.out.printf("%8s %-8s %6d %-6d %8f %-8.2f :) \n", "abc", "def", 123, 456, pi, pi); System.out.printf("%8s %-8s %6d %-6d", "abcdef", "ghijkl", 12345, 6789); Output: abc def 123 456 3.141593 3.14 :) abcdef ghijkl 12345 6789

Simple Java I/O Part V Serialization 16-Apr-18

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

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

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

Part III JFileChoosers Simple Java I/O Part III JFileChoosers 16-Apr-18

About JFileChoosers The JFileChooser class displays a window from which the user can select a file The dialog window is modal--the application cannot continue until it is closed Applets cannot use a JFileChooser, because applets cannot access files

Typical JFileChooser window

JFileChooser constructors Creates a JFileChooser starting from the user’s directory JFileChooser(File currentDirectory) Constructs a JFileChooser using the given File as the path JFileChooser(String currentDirectoryPath) Constructs a JFileChooser using the given path

Useful JFileChooser methods I int showOpenDialog(Component enclosingJFrame); Asks for a file to read; returns a flag (see below) int showSaveDialog(Component enclosingJFrame); Asks where to save a file; returns a flag (see below) Returned flag value may be: JFileChooser.APPROVE_OPTION JFileChooser.CANCEL_OPTION JFileChooser.ERROR_OPTION

Useful JFileChooser methods II File getSelectedFile() showOpenDialog and showSaveDialog return a flag telling what happened, but don’t return the selected file After we return from one of these methods, we have to ask the JFileChooser what file was selected If we are saving a file, the File may not actually exist yet—that’s OK, we still have a File object we can use

Using a File Assuming that we have successfully selected a File: File file = chooser.getSelectedFile(); if (file != null) { String fileName = file.getCanonicalPath(); FileReader fileReader = new FileReader(fileName); BufferedReader reader = new BufferedReader(fileReader); } File file = chooser.getSelectedFile(); if (file != null) { String fileName = file.getCanonicalPath(); FileOutputStream stream = new FileOutputStream(fileName); writer = new PrintWriter(stream, true); }

The End “There is no reason anyone would want a computer in their home.” --Ken Olson, President/founder of Digital Equipment Corp., 1977 “I think there is a world market for maybe five computers.” --Thomas Watson Chairman of IBM,| 1943