November 10, 2005Input and Output1 of 26 Input and Output String I/O Console I/O File I/O.

Slides:



Advertisements
Similar presentations
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.
Advertisements

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.
CS102--Object Oriented Programming
10-1 Writing to a Text File When a text file is opened in this way, a FileNotFoundException can be thrown – In this context it actually means that the.
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.
Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Objects, Methods, Parameters, Input Lecture 5, Thu Jan
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
Evan Korth Scanner class Evan Korth NYU. Evan Korth Java 1.5 (5.0)’s Scanner class Prior to Java 1.5 getting input from the console involved multiple.
Files and Streams CS 21a Chapter 11 of Horstmann.
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,
Lecture 3 Java Basics Lecture3.ppt.
File I/O There’s more to life than the keyboard. Interactive vs. file I/O All of the programs we have seen or written thus far have assumed interaction.
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.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
Strings as objects Strings are objects. Each String is an instance of the class String They can be constructed thus: String s = new String("Hi mom!");
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.
1 CSE 142 Lecture Notes Interactive Programs with Scanner Chapter 4 Suggested reading: Suggested self-checks: Section 4.10 #1-4 These lecture.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Io package as Java’s basic I/O system continue’d.
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.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
Console Input & Output CSS 161: Fundamentals of Computing Joe McCarthy 1.
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.
CHAPTER 3 GC Java Fundamentals. 2 BASICS OF JAVA ENVIRONMENT  The environment  The language  Java applications programming Interface API  Various.
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,
Winter 2006CISC121 - Prof. McLeod1 Last Time Misc. useful classes in Java: –String –StringTokenizer –Math –System.
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
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.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Can we talk?. In Hello World we already saw how to do Standard Output. You simply use the command line System.out.println(“text”); There are different.
Miscellaneous topics Chapter 2 Savitch. Miscellaneous topics Standard output using System.out Input using Scanner class.
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
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.
Chapter 10 Text Files Section 10.2 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
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.
CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.
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.
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.
COP 2551 Introduction to Object Oriented Programming with Java Topics –Introduction to the Java language –Code Commenting –Java Program Structure –Identifiers.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
CSC 211 Java I File I/O and more methods. Today’s plan Homework discussion Reading lines from files Writing lines to files All of the above, using methods.
Streams & File Input/Output (I/O)
CMSC 202 Text File I/O.
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II
Strings and File I/O.
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
I/O Streams- Basics Byte Streams and Character Streams
CSS161: Fundamentals of Computing
BIT115: Introduction to Programming
Program Style Console Input and Output
CSS 161: Fundamentals of Computing
Introduction to Classes and Methods
File I/O ICS 111: Introduction to Computer Science I
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
Presentation transcript:

November 10, 2005Input and Output1 of 26 Input and Output String I/O Console I/O File I/O

November 10, 2005Input and Output2 of 26 Strings We’ve used strings before, but usually as literals –e.g. new Frame(“xterm”); We can use strings like this, but they are really objects –String s = new String(); Strings define some very useful methods –substring(int start, int end) Returns a substring made up of the characters from index start to index end-1 in the original string –equals(String otherString) Checks to see if two strings are the same character for character Use this instead of the == operator, which checks to see if the memory addresses are the same –toUpperCase() Makes all characters upper case –See the javadocs for more useful methods October 25, 2005

November 10, 2005Input and Output3 of 26 String Concatenation We often want to stick one string on the end of another This is known as concatenation –since it is used so often, java lets us use the + operator rather than call a method String first = “Joe”; String last = “Somebody”; System.out.println(first + last); This will print out JoeSomebody –let’s fix that: System.out.println(first + “ “ + last); Now it will print out Joe Somebody

November 10, 2005Input and Output4 of 26 Comparing Strings Let’s see how to compare two strings String student = “Sara”; String other_student = “sara”; other_student = student.toLowerCase(); student == other_student returns false What’s going on here? –the == operator is checking memory addresses –we want to compare the characters that make up the strings Use equals(String other) ! student.equals(other_student) returns true

November 10, 2005Input and Output5 of 26 Console I/O Pre-GUI Interface for communication with computer –Type commands –Receive output as text No clicking required! –Edit code –Compile –Run programs –Data entry Keyboard/Console Input –Data typed into a console window by user Console Output –Data displayed in window by program Collectively referred to as Console I/O

November 10, 2005Input and Output6 of 26 Console Output in Java Magic! Platform specific, hidden by Java Console window represented by an Object –System.out –Public instance variable in System class Instance of PrintStream class Never throws exceptions! –Always open, always ready for output –Part of Java’s policy: “Write Once, Run Anywhere”

November 10, 2005Input and Output7 of 26 System.out.print –Writes a message to the console –System.out.print(“CS is neat!”); Message will appear on screen with prompt directly to the right System.out.print ing That looks ugly! How can we fix it? Java fixes it for us! Use System.out.println instead!

November 10, 2005Input and Output8 of 26 Prettier print ing Use System.out.println ! System.out.println(“CS is neat!”); Java will automatically add a newline character (‘ \n ’) at the end of the message: You can use the newline character too –Insert ‘ \n ’ wherever you want the line to break System.out.print(“CS\nis\nneat!\n”); –Java will add three newline characters –Text prints on four lines: CS15 is neat! –System.out.print(“CS15 is neat!\nYeah!”); –Prints out: CS15 is neat! Yeah!

November 10, 2005Input and Output9 of 26 More print ing We’re tired of printing String s –Can we print other types of values? –Of course! These methods can take different types of arguments –boolean s, int s, double s, or Object s import java.awt.geom.*; public class OutputDemo { public OutputDemo() { System.out.println(“Begin demo:”); System.out.print(“Print an int: ”); System.out.println(12); System.out.println(“Two booleans:”); System.out.println(true); System.out.println(false); System.out.print(“A double: ”); System.out.println(Math.PI); Ellipse2D.Double e = new Ellipse2D.Double(); e.setFrame(30, 40, 50, 60); System.out.println(“An object:”); System.out.println(e); } public static void main(String[] args) { OutputDemo app = new OutputDemo(); } }

November 10, 2005Input and Output10 of 26 OutputDemo console output Begin demo: Print an int: 12 Two booleans: True False A double: An object: 08 It may seem like printing out Object s isn’t very useful –most of the time it’s just a (seemingly) random string of letters and numbers –but... you can use it to check for null ! The next time you get a NullPointerException –try printing out the object you think might be null –the next time you run your program, check what gets printed out –if it says “ null ” right before the exception is thrown, you know that you need to initialize that object

November 10, 2005Input and Output11 of 26 Console Input in Java We have seen how to WRITE to the console using Java built-in commands What if we want our program to be able to READ user input from a console? –You guessed it! –System.in Public instance variable in System class Just like System.out Always ready to use Requires no initialization in code you write There are a few differences…

November 10, 2005Input and Output12 of 26 Scanner s Instead of reading directly from System.in, use a Scanner –Always have to tell the Scanner what to read –Instantiate it with a reference to read from System.in java.util.Scanner scanner = new java.util.Scanner(System.in); What does the Scanner do, and why do I need one? –Breaks down input into manageable units, called tokens Instead of drinking from the fire hose, we get passed nicely packaged bottles of water Scanner scanner = new Scanner(System.in); String userInput = scanner.nextLine(); nextLine() grabs everything typed into the console until the user enters a carriage return (hits the “Enter” key) –Tokens are the size of a line input and labeled String

November 10, 2005Input and Output13 of 26 Application of Console I/O We can write other data types, not just Strings –We can also read them! import java.util.*; public class EchoAge { public EchoAge() { System.out.print(“Enter your name: “); Scanner scan = new Scanner(System.in); String name = scan.nextLine(); System.out.print(“Enter your age: “); int age = scan.nextInt(); System.out.println(name + “ is “ + age + “ years old.”); } public static void main(String[] args) { EchoAge app = new EchoAge(); } }

November 10, 2005Input and Output14 of 26 Sample run and more methods If Mike runs this program, the console would show: $ java EchoAge Enter your name: Mike Enter your age: 20 Mike is 20 years old. $ What else can Scanner s read? To read in a: Use Scanner method booleanboolean nextBoolean() doubledouble nextDouble() floatfloat nextFloat() intint nextInt() longlong nextLong() shortshort nextShort() String (appearing in the next line, up to ‘\n’) String nextLine() String (appearing in the line up to next ‘ ‘, ‘\t’, ‘\n’) String next()

November 10, 2005Input and Output15 of 26 Scanner Exceptions InputMismatchException –Thrown by all nextType() methods –Token cannot be translated into a valid value of specified type –Scanner does not advance to the next token, so that this token can still be retrieved Handling this Exception –Prevent it Test next token by using a hasNextType() method Doesn’t advance the token, just checks and verifies type of next token –boolean hasNextBoolean() –boolean hasNextDouble() –boolean hasNextFloat() –boolean hasNextInt() –boolean hasNextLong() –boolean hasNextShort() –boolean hasNextLine() –Etc… –See the javadocs for more info about Scanner methods! –Catch it Handle the Exception once you catch it

November 10, 2005Input and Output16 of 26 File Overview What is a file? –a collection of data with a name –allows for long-term storage –has a name associated with it so that it can be found later Motivation: –often when working with computers we would like to be able to save what we’re working on and come back to it later –would like to be able to save settings and options –would like to be able to transfer data between computers

November 10, 2005Input and Output17 of 26 File Representation From the point of view of an object-oriented programmer, a file is an object with properties and methods Properties include, among other things: –it’s location in long-term memory (called the path) e.g. “/home/coolStuff/csProjects/” –a file’s name e.g. “App.java” –when it was last modified –whether or not it is a directory or just a file Operations include, among other things: –accessors and mutators for the path and name –operations to open and close files –operations to read and write to files (more on this shortly…)

November 10, 2005Input and Output18 of 26 Types of Files You’ve probably been exposed to files of different “types” i.e., they must be opened by different programs There are, however, two fundamental types of files Text files –contain characters you can type on the keyboard words numbers words in other alphabets the source files (*.java) of your programs are text files Binary files –may include text, but also include some symbols that cannot be represented as text –usually must be interpreted by another program, or can actually be executed! your compiled class files (*.class) are binary files the program “javac” is an executable binary file most pictures (*.jpg or *.gif) are binary files For the rest of this lecture, we will be concerning ourselves with text files

November 10, 2005Input and Output19 of 26 Creating a File In Java, there is a class which is used to represent a file. (Surprise! Surprise!) –The class is in the package java.io To create a file object we need only call the constructor of this class with the path to the file, or just the name of the file if it is in the current directory –e.g. new java.io.File(“testData.dat”); Note that this is not the same as actually creating a file on disk! –creating a new File object just connects our program to a file.

November 10, 2005Input and Output20 of 26 Like Drinking from a Fire Hose That’s all well and good, but how do we access the text in a file? Answer: with streams! The sequence of bytes flowing to or from an open file is referred to as a stream –this is true for both binary and text files –again, from the standpoint of an object oriented programmer, streams are just objects with properties and capabilities There are various kinds of streams –InputStream s, OutputStream s, PrintStream s, etc… –all are meant for different applications

November 10, 2005Input and Output21 of 26 What can Streams Do? All streams just represent a collection bytes –these bytes are not directly accessible, however Input streams allow you to read one or more bytes from a stream – int read(byte[] b, int offset, int len) –read len bytes starting from offset into the array b Output streams allow you to write one or more bytes to a stream –void write(byte[] b, int offset, int len) –write len bytes from b starting from offset into the stream But these methods are a bit… clumsy –to write a piece of text to a file, we would have to create a String, get an array of bytes which represents that String, and write that array to an open stream for that file If we’re dealing with text files, it would be nice to be able to work with files directly in terms of String s…

November 10, 2005Input and Output22 of 26 The Final Piece of the Puzzle Lucky for us, Java provides classes to make reading and writing to streams easy Readers and Writers exist to provide convenient ways to work with character streams –LineNumberReader / Writer –FileReader / Writer –BufferedReader / Writer –PipedReader / Writer –etc. All readers and writers extend from the abstract classes Reader and Writer –all must implement read or write, respectively –but most implement other helper methods or convenience constructors Thanks, Java! We are finally ready… let’s see some code

November 10, 2005Input and Output23 of 26 Let’s See an example… Let’s do something simple. We want to read in every line of a plain-text file and spit it back out to the console public class FileToConsole { public FileToConsole() { // Connect to the file called testData.dat // in the current directory File file = new File("testData.dat"); FileReader fileReader = null; try { // Must try-catch getting reader // because here we are actually // opening the file fileReader = new FileReader(file); } catch(FileNotFoundException e) { // Could not find the file, so // display an error and exit gracefully System.out.println("Could not open file, exiting."); System.exit(0); } // Class continued on the next page

November 10, 2005Input and Output24 of 26 Example continued… // Use a LineNumberReader to get input one // line at a time LineNumberReader lineReader = new LineNumberReader(fileReader); String line; try { // Repeat reading into line until // readLine() returns null while((line = lineReader.readLine()) != null) { // Print out the line we just read System.out.println(line); } } catch(IOException e) { // Again, if we get an error, print a // message System.out.println("IOException while reading file."); } finally { // Cleanup by closing our readers fileReader.close(); lineReader.close(); } } } // End of class FileToConsole

November 10, 2005Input and Output25 of 26 Writing to a file Now we want to write from console to a file: public class ConsoleToFile { public ConsoleToFile() { // Connect to a file named outputData.dat // in the current directory File file = new File("outputData.dat"); PrintWriter fileWriter = null; try { // Must try-catch getting writer // because here we are actually opening // the file fileWriter = new PrintWriter(file); } catch(FileNotFoundException e) { // Print a message and exit gracefully System.out.println("Could not open file. Exiting."); System.exit(0); } // Continued on next slide

November 10, 2005Input and Output26 of 26 Writing continued // New reader for the stream System.in BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); String line = ""; System.out.println("Enter data for file, one line at a time. q to quit."); try { // Read in until we hit a ‘q’ while(line.equals("q") == false) { // Read in a line from the console line = in.readLine(); // Write it out to a file fileWriter.println(line); } } catch(IOException e) { System.out.println("IOException while reading file."); } finally { fileWriter.close(); in.close(); } } } // End of class ConsoleToFile

November 10, 2005Input and Output27 of 26