Java Input/Output (I/O)

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.
LECTURE 17 C++ Strings 18. 2Strings Creating String Objects 18 C-string C++ - string \0 Array of chars that is null terminated (‘\0’). Object.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
 We can use a combination of the File and FileOutputStream to write a series of bytes to a file.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
Class Decimal Format ► Import package java.text ► Create DecimalFormat object and initialize ► Use method format ► Example: import java.text.DecimalFormat.
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.
OOP&M - laboratory lectures1 OOP&M – LAB2 LABzwei: the Input.
1 Introduction to Console Input  Primitive Type Wrapper Classes  Converting Strings to Numbers  System.in Stream  Wrapping System.in in a Buffered.
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.
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.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Java I/O Input: information brought to program from an external source
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.
Georgia Institute of Technology Speed part 3 Barb Ericson Georgia Institute of Technology May 2006.
Two Ways to Store Data in a File Text format Binary format.
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.
Console Input. So far… All the inputs for our programs have been hard-coded in the main method or inputted using the dialog boxes of BlueJ It’s time to.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Extensible Arrays: Vectors and StringBuffers Problem Set:Assignment #1 due Tuesday, Feburary 13 Wellesley College CS230 Lecture 05 Monday, February.
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.
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.
I/O in Java Dennis Burford
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
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.
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Lecture 5 I/O and Parsing
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.
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.
CSCI 1100/1202 January 23, Class Methods Some methods can be invoked through the class name, instead of through an object of the class These methods.
1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as.
java.io supports console and file I/O
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
Lecture 5 Text File I/O; Parsing.
Lesson 8: More File I/O February 5, 2008
Introduction to programming in java
Program Input/Output (I/O)
Java Exceptions and I/O
CHAPTER 5 JAVA FILE INPUT/OUTPUT
Lecture Note Set 1 Thursday 12-May-05
I/O Basics.
Creating and Modifying Text part 2
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Streams and File I/O Chapter 14.
JAVA IO.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Reading and Writing Text Files
L3. Necessary Java Programming Techniques
Unit 6 Working with files. Unit 6 Working with files.
I/O and Applet from Chapter 12
Web Design & Development Lecture 8
Exception Handling Contents
ECE 122 April 14, 2005.
EEC 484/584 Computer Networks
Presentation transcript:

Java Input/Output (I/O) Wellesley College CS230 Lecture 04 Thursday, February 8 Handout #11 (Revised, Monday February 11) Problem Set: Assignment #1 due Tuesday, Feburary 13

What is Input/Output (I/0)? I/O is any means of receiving information from or transmitting information to user/file system/web. Today we focus on textual information that can be entered/displayed in Linux shell. Later in the semester we will cover Graphical User Interfaces (GUIs).

Some examples of File I/O in Linux [fturbak@puma utils] cat ../text/cat-in-hat-4.txt The sun did not shine. It was too wet to play. So we sat in the house All that cold, cold, wet day. [fturbak@puma utils] wc ../text/cat-in-hat-4.txt 23 100 ../text/cat-in-hat-4.txt [fturbak@puma utils] wc ../text/cat-in-hat.txt 349 1620 7440 ../text/cat-in-hat.txt [fturbak@puma utils] cp ../text/cat-in-hat.txt copycat [fturbak@puma utils] wc copycat 349 1620 7440 copycat

Our Goal: Similar Operations in Java import java.io.*; // Import classes from the Java I/O package import java.net.*; // Import classes from the Java web package public class FileOps { // We will write all of our code in this class, which can // be found in your ~/cs230/utils/FileOps.java file. }

Reading File Contents Into a String public static String fileToString (String infile) { try { BufferedReader reader = new BufferedReader(new FileReader(infile)); // create a new file reader String result = ""; // variable for accumulating string from file; // next lecture, we’ll see a StringBuffer is better for this String line = reader.readLine(); // read the first line of the file. while (line != null) { // line becomes null at end of file result = result + line + '\n'; // readLine() omits the newline character, so add it back in line = reader.readLine(); // read the next line of the file } reader.close(); // close the file reader return result; } catch (IOException ex) { System.out.println(ex); // Handle file-not-found by displaying message return ""; // Return the empty string if file not found

Displaying File Contents (like Linux cat) /** A simple version of a method that displays file contents */ public static void displayFile (String infile) { System.out.println(fileToString(infile)); } [fturbak@puma utils] java FileOps displayFile ../text/cat-in-hat-4.txt The sun did not shine. It was too wet to play. So we sat in the house All that cold, cold, wet day.

A More Efficient displayFile() /** This version of displayFile() avoids reading entire file into a String object in Java memory. But it’s way more complex! The simpler version is fine for many applications. */ public static void displayFile (String infile) { try { BufferedReader reader = new BufferedReader(new FileReader(infile)); String line = reader.readLine(); // Read the first line of the file. while (line != null) { // Line becomes null at end of file System.out.println(line); line = reader.readLine(); // Read the next line of the file } reader.close(); } catch (IOException ex) { System.out.println(ex);

Creating a File from a String /** Writes the contents string to the file named by outfile. Displays an errors message if outfile cannot be created. */ public static void stringToFile (String outfile, String contents) { try { BufferedWriter writer = new BufferedWriter(new FileWriter(outfile)); // create a new file writer writer.write(contents); // write contents string to file writer.close(); // close file writer } catch (IOException ex) { System.out.println(ex); // Handle file-not-found }

Copying Files (like Linux cp) /** A simple version of a method that copies infile to outfile */ public static void copyFile (String infile, String outfile) { stringToFile(outfile, fileToString(infile)); } [fturbak@puma utils] java FileOps copyFile ../text/cat-in-hat-4.txt copycat-4 [fturbak@puma utils] java FileOps displayFile copycat-4 The sun did not shine. It was too wet to play. So we sat in the house All that cold, cold, wet day. We could avoid the large intermediate string of copyFile() by expanding fileToString() and writing one line at a time.

wordCount() (like Linux wc) /** A simple version of a Linux-like word count (wc) method */ public static void wordCount (String infile) { String contents = fileToString(infile); int chars = contents.length(); // number of chars in file int lines = contents.split("\n").length; // number of lines in file int words = contents.split("\\s+").length; // contents.split("\\s+") splits contents around every // substring of one or more whitespace chars. System.out.println(lines + "\t" + words + "\t" + chars + "\t" + infile); } [fturbak@puma utils] java FileOps wordCount ../text/cat-in-hat.txt 1620 7440 ../text/cat-in-hat.txt [fturbak@puma utils] wc ../text/cat-in-hat.txt 349 1620 7440 ../text/cat-in-hat.txt Again, we can avoid the large intermediate string of wordCount() by expanding fileToString() and processing one line at a time.

Testing wordCount() /** A simple version of a Linux-like word count (wc) method */ public static void wordCount (String infile) { String contents = fileToString(infile); int chars = contents.length(); // number of chars in file int lines = contents.split("\n").length; // number of lines in file int words = contents.split("\\s+").length; // contents.split("\\s+") splits contents around every // substring of one or more whitespace chars. System.out.println(lines + "\t" + words + "\t" + chars + "\t" + infile); }

Input Streams IO comes in InputStreams What you read is unformatted The keyboard: System.in A file: FileInputStream() The web: url.openStream() What you read is unformatted Format it into chars with an InputStreamReader For a file you use FileReader (String filename) What you read has unpredictable length Restrict it into lines with a BufferReader

Reading lines from an Input Stream public static String readLineFromInputStreamReader (InputStreamReader isReader) { try { BufferedReader reader = new BufferedReader(isReader); return reader.readLine(); } catch (IOException ex) { System.out.println(ex); return ""; }

Reading lines from other Sources public static String readLineFromFile (String infile) throws IOException { InputStreamReader fr = new FileReader(infile); return readLineFromInputStreamReader(fr); } public static String readLineFromURL (String urlName) throws IOException { InputStreamReader ir = new InputStreamReader(new URL(urlName).openStream()); return readLineFromInputStreamReader(ir); public static String readLineFromKeyboard (String prompt) throws IOException { System.out.println(prompt); InputStreamReader ir = new InputStreamReader(System.in);