I/O in Java Dennis Burford

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.
1 Streams and Input/Output Files Part 3. 2 Handling Primitive Data Types The basic input and output streams provide read/write methods that can be used.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 12 File Input and Output.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
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.
1 File Output. 2 So far… So far, all of our output has been to System.out  using print(), println(), or printf() All input has been from System.in 
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.
1 Text File I/O  I/O streams  Opening a text file for reading  Closing a stream  Reading a text file  Writing and appending to a text file.
COMP 14 Introduction to Programming Mr. Joshua Stough February 2, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
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.
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.
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.
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.
CIS 068 JAVA I/O: Streams and Files. CIS 068 I/O Usual Purpose: storing data to ‘nonvolatile‘ devices, e.g. harddisk Classes provided by package java.io.
Two Ways to Store Data in a File Text format Binary format.
CIS 260: App Dev I. 2 Objects and Reference Variables n Predefined Java classes you have used:  String —for defining and manipulating strings  Integer.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
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.
1 Java Console I/O Introduction. 2 Java I/O You may have noticed that all the I/O that we have done has been output The reasons –Java I/O is based on.
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.
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.
Programs & Data Files Notes Data information processed by word processing, spreadsheet or other application programs are stored as data files. Java programs,
Programming and Problem Solving With Java Copyright 1999, James M. Slack Chapter 6 Using Classes: Dates and I/O Streams Date, DateFormat, GregorianCalendar.
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.
File IO Basics By Dan Fleck Coming up: Data Streams.
Two Ways to Store Data in a File  Text format  Binary format.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
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.
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.
 Learn about computer files  Use the Path class  Learn about  Streams  Buffers  file organization  Use Java’s IO classes to write to and read from.
1 / 65 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 12 Programming Fundamentals using Java 1.
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.
Programs & Data Files Notes Data information processed by word processing, spreadsheet or other application programs are stored as data files. Java.
Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that.
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.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
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.
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
OO Design and Programming II I/O: Reading and Writing
Lesson 8: More File I/O February 5, 2008
Interactive Standard Input/output
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Reading and Writing Text Files
Chapter 6 Using Classes: Dates and I/O Streams
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
File Input and Output.
EEC 484/584 Computer Networks
Presentation transcript:

I/O in Java Dennis Burford

Input and Output Obtaining input: –Using BasicIo methods. –Through a GUI Producing output: –Using System.out methods ( System.out.println() ) –Through a GUI Other input/output: files, sockets etc.

Streams Java uses the concept of Streams for I/O Data flows from a Writer to a Reader ReaderWriter Stream

Why Streams? Stream generalizes input & output –Keyboard electronics different from disk –Input stream makes keyboard and files seem the same to a Reader Input Stream Reader

Simplified Keyboard Input… “Java: First Contact” uses BasicIo class –String name = BasicIo.readString(); –int age = BasicIo.readInteger(); Slack textbook uses Keyboard class –String name = Keyboard.readString(); –int age = Keyboard.readInt();

Simplified Keyboard Input… Both BasicIo and Keyboard are wrapper classes used to hide detail. In reality, both classes use System.in and other low-level Java classes to operate.

System class System class is inside java.lang package Contains 2 variables: public static final InputStream in; public static final PrintStream out; System.in is usually connected to the user’s keyboard. System.out is usually connected to the user’s screen.

Using System.in System.in is an InputStream Can use System.in many ways –Directly (low-level access) –Through layers of abstraction (high-level access)

Using System.in read() method reads one character at a time. Returns an int Returns –1 for EOF (End of File = Ctrl-Z)

Using System.in public static void main(String[] args) throws java.io.IOException { char character; // Prompt for a character and read it System.out.print("Enter a character: "); System.out.flush(); character = (char) System.in.read(); // Display the character typed System.out.println(); System.out.println("You typed " + character); }

Using System.in int intChar = System.in.read(); while (intChar != -1) { // Convert to character char character = (char) intChar; System.out.println("Next character is " + character); // Get next one intChar = System.in.read(); }

Reading Strings No String-reading methods in System.in To read strings from keyboard, first wrap System.in inside InputStreamReader object: InputStreamReader ISReader = new InputStreamReader(System.in);

Reading Strings

Next, wrap InputStreamReader object in BufferedReader object: InputStreamReader ISReader = new InputStreamReader(System.in); BufferedReader BufReader = new BufferedReader(ISReader);

Reading Strings Can combine these into a single statement: BufferedReader BufReader = new BufferedReader(new InputStreamReader(System.in));

Reading Strings Can combine these into a single statement: BufferedReader BufReader = new BufferedReader(new InputStreamReader(System.in)); InputStream InputStreamReader BufferedReader

Reading Strings Methods in BufferedReader –read() –readLine() Read a string by using readLine() method: String str = BufReader.readLine();

Reading Strings

InputStreamReader, BufferedReader in java.io.* Skeleton for reading: import java.io.*; class ClassName { public static void main(String[] args) throws java.io.IOException { // Create a buffered input stream and attach it to standard // input BufferedReader BufReader = new BufferedReader(new InputStreamReader(System.in));... }

Example: Reading User’s Name // Reads a user's first name and last name. // Demonstrates use of InputStreamReader, // BufferedReader and the readLine() method. import java.io.*; class ReadInputAsString { public static void main(String[] args) throws java.io.IOException { String firstName, lastName; // Create an input stream and attach it to the standard // input stream BufferedReader BufReader = new BufferedReader(new InputStreamReader(System.in));

Example: Reading User’s Name // Read a line from the user as a String System.out.print("Enter your first name: "); System.out.flush(); firstName = BufReader.readLine(); // Read a line from the user as a String System.out.print("Enter your last name: "); System.out.flush(); lastName = BufReader.readLine(); // Display the strings System.out.println(); System.out.println("Your name is" + firstName + lastName); }

Example: Reading User’s Name // Read a line from the user as a String System.out.print("Enter your first name: "); System.out.flush(); firstName = BufReader.readLine(); // Read a line from the user as a String System.out.print("Enter your last name: "); System.out.flush(); lastName = BufReader.readLine(); // Display the strings System.out.println(); System.out.println("Your name is" + firstName + lastName); } Enter your first name: Linda Enter your last name: Jones Your name is Linda Jones

Formatting Numbers Alternative to Integer.parseInt() etc. NumberFormat –Object factory: use getInstance() –parse() takes a string and returns a Number –parse() throws java.text.ParseException General Number class –Return value using intValue(), doubleValue() etc.

Formatting Numbers from Kbd NumberFormat formatter = NumberFormat.getInstance(); BufferedReader BufReader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter an integer: "); System.out.flush(); String response = BufReader.readLine(); Number numberObj = formatter.parse(response); int numberInt = numberObj.intValue();

Formatting Numbers from Kbd NumberFormat formatter = NumberFormat.getInstance(); BufferedReader BufReader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter an integer: "); System.out.flush(); String response = BufReader.readLine(); Number numberObj = formatter.parse(response); int numberInt = numberObj.intValue(); Combine

Formatting Numbers from Kbd NumberFormat formatter = NumberFormat.getInstance(); BufferedReader BufReader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter an integer: "); System.out.flush(); int numberInt = formatter.parse( BufReader.readLine() ).intValue();

Formatting Numbers from Kbd NumberFormat formatter = NumberFormat.getInstance(); BufferedReader BufReader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter an integer: "); System.out.flush(); int numberInt = formatter.parse( BufReader.readLine() ).intValue(); Don’t forget to throw or catch java.text.ParseException

Input Streams: Multiple Values To read several values on one line –Use StringTokenizer object –Breaks one string into component parts –Must still convert numbers (if necessary) StringTokenizer –Constructor takes string –nextToken() method –hasMoreTokens() method

Input Streams: Multiple Values StringTokenizer tokenizer = new StringTokenizer("42 58"); String token; token = tokenizer.nextToken(); System.out.println(token); // Displays 42 token = tokenizer.nextToken(); System.out.println(token); // Displays 58 BETTER… StringTokenizer tokenizer = new StringTokenizer("42 58"); while (tokenizer.hasMoreTokens()) { System.out.println(tokenizer.nextToken()); }

FILES

Overview of Files How they are accessed: –sequential: data items must be accessed in the order in which they are stored (ie. start at the beginning and pass through all the items) –direct (or random): items are accessed by specifying their location How information is represented: –text files: data is stored in character form. –binary files: data is stored in internal binary form (faster and more compact than text files).

Types of Files Summer.txt Rough winds do shake the darling buds of May\n And Summer’s lease hath all too short a date\n Sometime too hot the eye of heaven shines,\n And oft is his gold complexion dimmed,\n And every fair from fair sometime declines... Numbers.dat Œpôw10Žé¿l%®ú€9câÜ(3xLenfˆx¹ª(Ͻ»¼øß:°µœŒ ÝçMÙ¾à:ˆqfõÑ>|èœ=L¶...

Text Files Text file –human-readable with simple tools (Notepad, Ready,...) –Each line terminated by end-of-line marker (‘\n’) –Example:.java files Easy to read and write text files –Advantage of "streams" approach to I/O –Use same classes and methods as System.in and System.out

Text Files: The File Class Need File object for each file program uses –File inFile = new File(”Summer.txt"); Purpose –Contains information about the file –A “go-between” for the file –Not the same as the file itself

Text Files: The File Class Methods in the File class –exists() : Tells if the file is there –canRead() : Tells if program can read the file –canWrite() : Tells if program can write to the file –delete() : Deletes the file –isDirectory() : Tells if file is really a directory name –isFile() : Tells if the file is a file (not a directory) –length() : Tells the length of the file, in bytes

Text Files: The File Class Methods in the File class –exists() : Tells if the file is there –canRead() : Tells if program can read the file –canWrite() : Tells if program can write to the file –delete() : Deletes the file –isDirectory() : Tells if file is really a directory name –isFile() : Tells if the file is a file (not a directory) –length() : Tells the length of the file, in bytes

import java.io.*; class TellIfExists { public static void main(String[] args) throws java.io.IOException { File myFile = new File(“Summer.txt”); if (myFile.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); } } // end main }

import java.io.*; class TellIfExists { public static void main(String[] args) throws java.io.IOException { File myFile = new File(“Summer.txt”); if (myFile.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); } } // end main }

import java.io.*; class TellIfExists { public static void main(String[] args) throws java.io.IOException { File myFile = new File(“Summer.txt”); if (myFile.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); } } // end main }

import java.io.*; class TellIfExists { public static void main(String[] args) throws java.io.IOException { File myFile = new File(“Summer.txt”); if (myFile.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); } } // end main }

import java.io.*; class TellIfExists { public static void main(String[] args) throws java.io.IOException { File myFile = new File(“Summer.txt”); if (myFile.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); } } // end main }

import java.io.*; class TellIfExists { public static void main(String[] args) throws java.io.IOException { File myFile = new File(“Summer.txt”); if (myFile.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); } } // end main }

Text Files: Reading from a File Before reading, make sure –File exists and is readable inFile.exists() && inFile.canRead() Attach file to a stream –FileReader object: knows how to read stream from a file –Wrap FileReader object in BufferedReader object BufferedReader works on files just like System.in –read() : read a single character, or -1 if EOF –readLine() : read a line, or null if EOF

File FileReader BufferedReader

// Initialize the file variable File inFile = new File(”Summer.txt"); // Make sure the file can be read from if (inFile.exists() && inFile.canRead()) { // Create input stream and attach to the file BufferedReader BufReader = new BufferedReader(new FileReader(inFile)); // Read from file stream same way as reading // from the keyboard String line = BufReader.readLine(); } else { // Error: Can't read from file }

// Initialize the file variable File inFile = new File(”Summer.txt"); // Make sure the file can be read from if (inFile.exists() && inFile.canRead()) { // Create input stream and attach to the file BufferedReader BufReader = new BufferedReader(new FileReader(inFile)); // Read from file stream same way as reading // from the keyboard String line = BufReader.readLine(); } else { // Error: Can't read from file }

// Initialize the file variable File inFile = new File(”Summer.txt"); // Make sure the file can be read from if (inFile.exists() && inFile.canRead()) { // Create input stream and attach to the file BufferedReader BufReader = new BufferedReader(new FileReader(inFile)); // Read from file stream same way as reading // from the keyboard String line = BufReader.readLine(); } else { // Error: Can't read from file }

// Initialize the file variable File inFile = new File(”Summer.txt"); // Make sure the file can be read from if (inFile.exists() && inFile.canRead()) { // Create input stream and attach to the file BufferedReader BufReader = new BufferedReader(new FileReader(inFile)); // Read from file stream same way as reading // from the keyboard String line = BufReader.readLine(); } else { // Error: Can't read from file }

// Initialize the file variable File inFile = new File(”Summer.txt"); // Make sure the file can be read from if (inFile.exists() && inFile.canRead()) { // Create input stream and attach to the file BufferedReader BufReader = new BufferedReader(new FileReader(inFile)); // Read from file stream same way as reading // from the keyboard String line = BufReader.readLine(); } else { // Error: Can't read from file }

// Initialize the file variable File inFile = new File(”Summer.txt"); // Make sure the file can be read from if (inFile.exists() && inFile.canRead()) { // Create input stream and attach to the file BufferedReader BufReader = new BufferedReader(new FileReader(inFile)); // Read from file stream same way as reading // from the keyboard String line = BufReader.readLine(); } else { // Error: Can't read from file } line = “ Rough winds do shake the darling buds of May ”

Text Files: Reading from a File Can do same things we did with System.in –Read numbers ( NumberFormat ) –Read multiple “tokens” ( StringTokenizer )

Text Files: Writing to a File Before writing, make sure either... –File doesn't exist !outFile.exists() –Or file exists, and is writeable outFile.exists() && outFile.canWrite() Combine conditions !outFile.exists() || outFile.canWrite()

Text Files: Writing to a File Attach file to a stream –FileWriter object: knows how to write stream to a file –Wrap FileWriter object in BufferedWriter object –Wrap BufferedWriter object in PrintWriter object

File FileWriter BufferedWriter PrintWriter

// Initialize the file variable File outFile = new File(”New.txt"); // Make sure that the file either doesn't exist or // we can write to it if (!outFile.exists() || outFile.canWrite()) { // Create an output stream and attach it to the file PrintWriter pWriter = new PrintWriter(new BufferedWriter( new FileWriter(outFile))); // Write to the file pWriter.println( “This is the first line!” ); } else { // Error: Can't write to the file }

// Initialize the file variable File outFile = new File(”New.txt"); // Make sure that the file either doesn't exist or // we can write to it if (!outFile.exists() || outFile.canWrite()) { // Create an output stream and attach it to the file PrintWriter pWriter = new PrintWriter(new BufferedWriter( new FileWriter(outFile))); // Write to the file pWriter.println( “This is the first line!” ); } else { // Error: Can't write to the file }

// Initialize the file variable File outFile = new File(”New.txt"); // Make sure that the file either doesn't exist or // we can write to it if (!outFile.exists() || outFile.canWrite()) { // Create an output stream and attach it to the file PrintWriter pWriter = new PrintWriter(new BufferedWriter( new FileWriter(outFile))); // Write to the file pWriter.println( “This is the first line!” ); } else { // Error: Can't write to the file }

// Initialize the file variable File outFile = new File(”New.txt"); // Make sure that the file either doesn't exist or // we can write to it if (!outFile.exists() || outFile.canWrite()) { // Create an output stream and attach it to the file PrintWriter pWriter = new PrintWriter(new BufferedWriter( new FileWriter(outFile))); // Write to the file pWriter.println( “This is the first line!” ); } else { // Error: Can't write to the file }

// Initialize the file variable File outFile = new File(”New.txt"); // Make sure that the file either doesn't exist or // we can write to it if (!outFile.exists() || outFile.canWrite()) { // Create an output stream and attach it to the file PrintWriter pWriter = new PrintWriter(new BufferedWriter( new FileWriter(outFile))); // Write to the file pWriter.println( “This is the first line!” ); } else { // Error: Can't write to the file }

Text Files: Writing to a File System.out and pWriter both output streams –System.out is PrintStream object –pWriter is PrintWriter object –PrintStream and PrintWriter are almost identical ( PrintWriter is newer) –print(), println(), flush() work the same

Text Files: Writing to a File System.out and pWriter both output streams –System.out is PrintStream object –pWriter is PrintWriter object –PrintStream and PrintWriter are almost identical ( PrintWriter is newer) –print(), println(), flush() work the same pWriter.print("This goes "); pWriter.println("to the file");

Text Files: Writing to a File Once finished writing to the file, close it pWriter.close();

Java I/O Summary

Reading from Keyboard –BufferedReader( InputStreamReader( System.in )) Writing to Screen –System.out Reading from File –BufferedReader( FileReader( File )) Writing to File –PrintWriter( BufferedWriter( FileWriter( File )))