Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "November 10, 2005Input and Output1 of 26 Input and Output String I/O Console I/O File I/O."— Presentation transcript:

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

2 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

3 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

4 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

5 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

6 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”

7 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!

8 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!

9 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(); } }

10 November 10, 2005Input and Output10 of 26 OutputDemo console output Begin demo: Print an int: 12 Two booleans: True False A double: 3.141592653589793 An object: java.awt.geom.Ellipse2D$Double@e531 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

11 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…

12 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

13 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(); } }

14 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()

15 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

16 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

17 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…)

18 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

19 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.

20 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

21 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…

22 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

23 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

24 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

25 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

26 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

27 November 10, 2005Input and Output27 of 26


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

Similar presentations


Ads by Google