Program Input/Output (I/O)

Slides:



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

Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
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.
Today Assignment 2 is posted. Due the first Friday after Reading Week. (“Virtual” lecture looked at the use of try/catch and try with resources blocks.
Files and Streams. Goals To be able to read and write text files To be able to read and write text files To become familiar with the concepts of text.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 8: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
Files and Streams CS 21a. 10/02/05 L18: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 12 File Input and Output.
OOP&M - laboratory lectures1 OOP&M – LAB2 LABzwei: the Input.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
Java I/O – what does it include? Command line user interface –Initial arguments to main program –System.in and System.out GUI Hardware –Disk drives ->
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Reading/Writing Files, Webpages CS2110, Recitation 10 1.
Io package as Java’s basic I/O system continue’d.
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
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.
Two Ways to Store Data in a File Text format Binary format.
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.
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.
1 Streams Files are a computer’s long term memory Need ability for programs to –get information from files –copy information from program variables to.
CS61B L02 Using Objects (1)Garcia / Yelick Fall 2003 © UCB Kathy Yelick Handout for today: These lecture notes Computer Science 61B Lecture 2 – Using Objects.
Java Input/Output CSE301 University of Sunderland Harry Erwin, PhD Half Lecture.
File IO Basics By Dan Fleck Coming up: Data Streams.
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.
Characters, Strings, Reading Files CS2110, Week 2 Recitation.
Chapter 15 Text Processing and File Input/Output Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin,
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.
Reading/Writing Files, Webpages CS2110, Recitation 8 1.
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.
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.
Files and console applications Chapter 17 This chapter explains: What a file is How to read and write to files How to manipulate folder paths and file.
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.
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.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
GENERICS AND FILE HANDLING Saumya Srivastava (977934) Divyangana Pandey (977790) Shubhi Saxena (978108) Arka Das (962969) AHD05/15-16 AJA 21.
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.
Keerthi Nelaturu Url: site.uottawa.ca/~knela006
Lecture 8: I/O Streams types of I/O streams Chaining Streams
OO Design and Programming II I/O: Reading and Writing
File Input / Output.
Streams & File Input/Output (I/O)
Lesson 8: More File I/O February 5, 2008
Streams and File I/O.
University of Central Florida COP 3330 Object Oriented Programming
Strings and File I/O.
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
Creating and Modifying Text part 2
Chapter 13: File Input and Output
I/O Streams- Basics Byte Streams and Character Streams
Streams and File I/O Chapter 14.
Unit 6 Working with files. Unit 6 Working with files.
18 File i/o, Parsing.
I/O and Applet from Chapter 12
Web Design & Development Lecture 8
File Input and Output.
ECE 122 April 14, 2005.
EEC 484/584 Computer Networks
Chapter 8: Exceptions and I/O Streams
Presentation transcript:

Program Input/Output (I/O) CS2110 Recitation 8

Program Input/Output This is I/O Arguments Files Program Remote Machines This is I/O Java's I/O classes are in package java.io package java.nio To import the classes: import java.io.*; import java.nio.*; Console Return values

Files Files (and directories) are identified by paths File system on a hard disk is structured as a tree leaves are files (or empty directories) Internal nodes are directories (aka folders) First thing to talk about is File I/O, so you need to cover the basics of a file system

Interface Path An object of type Path contains the path name to a file or directory. Path is an interface because different operating systems handle files differently. For each OS, there is a class that implements Path To find out which class your OS uses, try p.getClas() A path can be absolute or relative. Absolute paths give the full path of the file. To find out what absolute paths look like on your machine, try p.toAbsolutepath() Relative paths define the location relative to some default location (in Java, the package directory) You should always use relative paths (otherwise your code won't work on other machines)

Class Paths An object of type Path contains the path name to a file or directory. Class Paths contains static methods for creating Path objects Path p = Paths.get("res","map1.xml"); Paths.get can take any number of arguments. Arguments define a path relative to the package in which the class resides. (e.g., res/map1.xml)

Class Files Class Files contains static methods to operate on the file/directory given by a path object. Class Files has lots of methods, e.g. exists(Path p) isReadable(Path p) createFile(Path p) delete(Path p) isWritable(Path p) size(Path p) … (lots more) … Open a browser and show them the API specs for class File, showing them briefly what methods are available. Show them the Eclipse program: Comment out all method calls in main except the call fileDec(), show them procedure fileDec, and run the main program.

Java I/O uses Streams Stream: a sequence of data values that is processed—either read or written—from beginning to end. Input streams represent an input source (e.g., a file you are reading from) Output streams represent an output destination (e.g., a file you are writing to)

A metaphor Streams are like conveyor belts in a factory or warehouse Input streams: take each item (e.g., a line from a file) off the conveyor belt and deal with it Output streams: generate each item (e.g., a line in a file) and then put it on the conveyor belt

Types of Streams Lots of different types of streams Byte Streams Raw Streams Blocking Streams Character Streams Buffered Streams NIO streams Object Streams

Input Streams InputStream and OutputStream are byte I/O streams that can be used for File I/O Read input stream for a file is by creating an instance of class InputStream: InputStream is= Files.newInputStream(p); is.read() // get next byte of file Too low-level! Don’t want to do byte by byte. Instead, use a buffered stream to read line by line This is self-explanatory. FileReader delivers 1 character at a time.

Buffered Streams Class BufferedReader creates a buffered stream from a raw stream (e.g., a InputStream object). You can also create a BufferedReader directly from a path. BufferedReader provides a method for reading one line at a time. InputStream is= Files.newInputStream(p); BufferedReader br= new BufferedReader(is); OR BufferedReader br= Files.newBufferedReader(p); String s= br.readLine(); // Store next line of file in s // (null if none) br.close(); // close stream when done

Pattern to read a file Always use this pattern to read a file! line= first line; while (line != null) { Process line; line= next line; } line= br.readLine(); while (line != null) { Process line } Be sure to emphasize the pattern for reading from a file. The first line is read before the loop, the loop continues until line s null. The body processes the line and then read the next one. EMPHASIZE THIS PATTERN

Example: counting lines in a file /** Return number of lines in file at path p. Throw IO Exception if problems encountered when reading */ public static int getSize(Path p) throws IOException { BufferedReader br= Files.newBufferedReader(p); int n= 0; // number of lines read so far String line= br.readLine(); while (line != null) { n= n+1; line= br.readLine(); } br.close(); return n; Always use this pattern to read a file! line= first line; while (line != null) { Process line; line= next line; } (write as while loop) Be sure to emphasize the pattern for reading from a file. The first line is read before the loop, the loop continues until line s null. The body processes the line and then read the next one. EMPHASIZE THIS PATTERN You can also show this code from the IOdemo class Don’t forget!

Output Streams Writing a file is similar. First, get a BufferedWriter: BufferedWriter bw= Files.newBufferedWriter(p); Default: create file if it doesn't exist, overwrite old files Can override defaults using options from Class StandardOpenOption Then use bw.write(“…”); to write a String to the file. bw.close(); // Don’t forget to close! Writing a file is just as easy, but it’s good to show them an example. Do this. Place a .java file with at least one // comment in it somewhere easily accessible on our harddrive. Show it to the students. Show them in the demo file procedure extract, look at it sec and how it works. Demo it. When you first run it, a JFileChooser window asks for a file. Navigate to and select the .java file A second JFileChooser window asks for the name of a file to write. If the Java file was xxx.java, then use the file name xxx.txt. And hit return The file will be created. Look ati Recommended: use a PrintWriter to write non-String objects and to access additional methods (e.g., println) Printwriter pw = new PrintWriter(Files.newBufferedWriter(p)); pw.println(6);

Standard Streams Standard streams are operating system features that read input from the keyboard and write output to the display Java supports these System.out System.in System.out is a PrintWriter System.in is an InputStream You've probably already used this! It's just an output stream.

Reading Remote Files Class URL in package java.net: URL url= new URL(“http://www. … …. /links.html); A URL (Universal Resource Locator) describes a resource on the web, like a web page, a jpg file, a gif file The “protocol” can be: http (HyperText Transfer Protocol) https ftp (File Transfer Protocol) The next two slides are meant to introduce class URL and its help in reading a webpage. Please embellish This discussion with your own knowledge of URLs. The next slides contains code to set up reading the lines of a webpage. The accompanying Eclipse package has a method that will read and print a number of lines of a page on the course website. When you execute that program, bring up the links.html page on a browser, so students can compare the webpage to the lines printed. Many students will not now about the language html, so go slowly, telling them what various tags mean.

Reading from an html web page Given is URL url= new URL(“http://www. … …. /links.html); To read lines from that webpage, do this: Create an InputStreamReader: InputStreamReader isr= new InputStreamReader(url.openStream()); Have to open the stream 2. Create a Buffered Reader: BufferedReader br= new BufferedReader(isr); 3. Read lines, as before, using br.readLine()