1 / 65 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 12 Programming Fundamentals using Java 1.

Slides:



Advertisements
Similar presentations
Lecture 15: I/O and Parsing
Advertisements

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.
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.
Copyright 2008 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: , 5.3 self-check: Ch. 6 #1-6.
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.
1 CS2200 Software Development Lecture 36: File Processing A. O’Riordan, 2008 (Includes slides by Lewis/Loftus 2205 and K. Brown )
Copyright 2008 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: , 5.3 self-check: Ch. 6 #1-6.
18 File handling1June File handling CE : Fundamental Programming Techniques.
1 CSE 142 Lecture Notes File input using Scanner Suggested reading: , Suggested self-checks: Section 6.7 # 1-11, These lecture.
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.
File I/O in Java CS 311, Winter File Basics Recall that a file is block structured. What does this mean? What happens when an application opens.
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!");
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.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 6: File Processing.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
2-1 CM0551 Week 3 The scanner class – file input A Spelling Checker Time and space requirements for various dictionary structures.
Using java’s Scanner class To read from input and from a file. (horstmann ch04 and ch 17)
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
Recitation 1 CS0445 Data Structures Mehmud Abliz.
1 Introduction to Java Brief history of Java Sample Java Program Compiling & Executing Reading: => Section 1.1.
Chapter 15 – Files I/O basics File I/O Classes File I/O Basic Operations Text File Output PrintWriter import Statement with a * Text File Input Scanner,
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,
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
I/O in Java Dennis Burford
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
CSci 111 – computer Science I Fall 2014 Cynthia Zickos WRITING A SIMPLE PROGRAM IN JAVA.
1 BUILDING JAVA PROGRAMS CHAPTER 6 DETAILS OF TOKEN-BASED PROCESSING.
BUILDING JAVA PROGRAMS CHAPTER 6 File Processing.
Java 1.5 The New Java Mike Orsega Central Carolina CC.
Unix Environment Input Output 2  List Content (ls) ◦ ls (list current directory) ◦ ls –all (include hidden files/folders)  Make directory (mkdir) ◦
A stream is a sequence of data. A stream is a flowing sequence of characters.
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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 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.
תוכנה 1 תרגול מס ' 4 שימוש במחלקות קיימות : קלט / פלט (IO)
Copyright 2010 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: 6.1 – 6.2, 5.4.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Lab 04-2 Objectives:  Understand what a file is.  Learn how to use the File class  Learn how to use the Scanner class to read from files  Learn about.
Java I/O 1. Java I/O (Input and Output) is used to process the input and produce the output based on the input. The java.io package contains all the classes.
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.
Introduction to programming in java
Building Java Programs Chapter 6 File Processing Copyright (c) Pearson All rights reserved.
OO Design and Programming II I/O: Reading and Writing
CMSC 202 Text File I/O.
Introduction to programming in java
Reading from a file A file is typically stored on your computers hard drive. In the simplest case, lets just assume it is text. For a program to use.
Streams and File I/O.
OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS
File Input and Output TOPICS File Input Exception Handling File Output.
I/O Basics.
File Input and Output TOPICS File Input Exception Handling File Output.
Programming in Java Files and I/O Streams
CSS161: Fundamentals of Computing
Објектно орјентисано програмирање
Introduction to Classes and Methods
Building Java Programs Chapter 6
18 File i/o, Parsing.
Input/output (I/O) import java.io.*;
File Handling in Java January 19
Input/output (I/O) import java.io.*;
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
Input/output (I/O) import java.io.*;
CIS 110: Introduction to Computer Programming
Presentation transcript:

1 / 65 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 12 Programming Fundamentals using Java 1

2 / 65 Input/Output (IO)

3 / 65 I/O  So far we have looked at modeling classes

4 / 65 I/O  So far we have looked at modeling classes  Not much in the way of Input...

5 / 65 Input  3 ways of providing input to the program:

6 / 65 Input  3 ways of providing input to the program:  Pass parameters directly to the program

7 / 65 Input  3 ways of providing input to the program:  Pass parameters directly to the program  Command-line input from the user

8 / 65 Input  3 ways of providing input to the program:  Pass parameters directly to the program  Command-line input from the user  Reading in files

9 / 65 Passing parameters  When running the program can directly pass parameters to it

10 / 65 Passing parameters  When running the program can directly pass parameters to it java ProgramName parameter1 parameter2...

11 / 65 Passing parameters public static void main(String[] args) { // args is the array of all parameters // args[0] would be the first parameter }

12 / 65 Passing parameters public static void main(String[] args) { // args is the array of all parameters // args[0] would be the first parameter } Let’s look at an example

13 / 65 Command-line input  Receive input from the console during execution

14 / 65 Command-line input  Receive input from the console during execution  Use the Scanner class

15 / 65 The Scanner class  Used for reading data

16 / 65 The Scanner class  Used for reading data  Constructors:  Scanner(InputStream) InputStream = System.in

17 / 65 The Scanner class  Used for reading data  Constructors:  Scanner(InputStream) InputStream = System.in  Scanner(String)

18 / 65 The Scanner class  Used for reading data  Constructors:  Scanner(InputStream) InputStream = System.in  Scanner(String)  Scanner(File)

19 / 65 The Scanner class  Methods:  boolean hasNext() : If scanner has more tokens

20 / 65 The Scanner class  Methods:  boolean hasNext() : If scanner has more tokens  String next() :Returns the next String  int nextInt() :Returns the next int  double nextDouble() : Returns the next double

21 / 65 The Scanner class  Methods:  boolean hasNext() : If scanner has more tokens  String next() :Returns the next String  int nextInt() :Returns the next int  double nextDouble() : Returns the next double  void useDelimiter(pattern: String) :Set’s the delimiting pattern (“ “ by default)

22 / 65 The Scanner class  Methods:  boolean hasNext() : If scanner has more tokens  String next() :Returns the next String  int nextInt() :Returns the next int  double nextDouble() : Returns the next double  void useDelimiter(pattern: String) :Set’s the delimiting pattern (“ “ by default)  void close():Closes the Scanner

23 / 65 Command-line input  Use the “next..” methods to read from the standard input

24 / 65 Command-line input  Use the “next..” methods to read from the standard input import java.util.Scanner; Scanner scanner = new Scanner(System.in); System.out.print(“Enter number1: “); double number1 = scanner.nextDouble(); System.out.print(“Enter number2: “); double number2 = scanner.nextDouble(); System.out.println(“The addition of the two numbers: “ + (number1 + number2));

25 / 65 File Input  Ability to read files essential to any language.

26 / 65 File Input  Ability to read files essential to any language.  Two ways to store data:  Text format:

27 / 65 File Input  Ability to read files essential to any language.  Two ways to store data:  Text format: Human-readable form Can be read by text editors

28 / 65 File Input  Ability to read files essential to any language.  Two ways to store data:  Text format: Human-readable form Can be read by text editors  Binary format: Used for executable programs Cannot be read by text editors

29 / 65 The File class  java.io package  Represents a “file” object  Used for input/output through data streams, the file system and serialization.

30 / 65 The File class  Constructors:  File(pathname: String):Creates a File object for the specified pathname. pathname = directory or file

31 / 65 The File class  Constructors:  File(pathname: String):Creates a File object for the specified pathname. pathname = directory or file  File(parent: String, child: String):Creates a File object for the child under the directory parent. child may be a filename or subdirectory.

32 / 65 The File class  Methods:  boolean exists() : If the file exists

33 / 65 The File class  Methods:  boolean exists() : If the file exists  boolean canRead() :If the file exists and we can read it  boolean canWrite() :If the file exists and we can write to it

34 / 65 The File class  Methods:  boolean exists() : If the file exists  boolean canRead() :If the file exists and we can read it  boolean canWrite() :If the file exists and we can write to it  void isDirectory() :if the object is a directory  void isFile() :if the object is a file

35 / 65 The File class  Methods:  boolean exists() : If the file exists  boolean canRead() :If the file exists and we can read it  boolean canWrite() :If the file exists and we can write to it  void isDirectory() :if the object is a directory  void isFile() :if the object is a file  String getName() :Returns the name of the file

36 / 65 The File class  Methods:  boolean exists() : If the file exists  boolean canRead() :If the file exists and we can read it  boolean canWrite() :If the file exists and we can write to it  void isDirectory() :if the object is a directory  void isFile() :if the object is a file  String getName() :Returns the name of the file  boolean delete() :Deletes the file and returns true if succeeded  renameTo (dest: File) :Tries to rename the file and returns true if succeeded

37 / 65 Reading Files  Use the Scanner class  new Scanner(File)

38 / 65 Reading Files  How does Scanner really work?

39 / 65 Reading Files  How does Scanner really work?  Breaks file contents into tokens  Uses a delimiter

40 / 65 Reading Files  How does Scanner really work?  Breaks file contents into tokens  Uses a delimiter  Delimiter by default is whitespace

41 / 65 Reading Files  How does Scanner really work?  Breaks file contents into tokens  Uses a delimiter  Delimiter by default is whitespace  Reads a token, converts it to the required type

42 / 65 Reading Files  How does Scanner really work?  Breaks file contents into tokens  Uses a delimiter  Delimiter by default is whitespace  Reads a token, converts it to the required type  Can change the delimiter – useDelimiter() method

43 / 65 Reading Files // Reads in the file and outputs all the tokens Scanner input = new Scanner(new File(“test.txt”)); while (input.hasNext()) { System.out.println(input.next()); }

44 / 65 Reading Files // Reads in the file and outputs all the tokens Scanner input = new Scanner(new File(“test.txt”)); while (input.hasNext()) { System.out.println(input.next()); } ERROR – WON’T COMPILE

45 / 65 Reading Files // Reads in the file and outputs all the tokens Scanner input = new Scanner(new File(“test.txt”)); while (input.hasNext()) { System.out.println(input.next()); } ERROR – WON’T COMPILE The constructor throws a FileNotFoundException

46 / 65 Reading Files // Reads in the file and outputs all the tokens try { Scanner input = new Scanner(new File(“test.txt”)); while (input.hasNext()) { System.out.println(input.next()); } } catch (FileNotFoundException fe) { fe.printStackTrace(); }

47 / 65 Reading files  Have to be careful. Suppose a file contains the line: 

48 / 65 Reading files  Have to be careful. Suppose a file contains the line:  What will be the contents of intValue and line after the following code is executed? Scanner in = new Scanner(new File(“test.txt”)); int intValue = in.nextInt(); String line = in.nextLine();

49 / 65 Reading files Scanner scanner = new Scanner(“file.txt”); Treats the String “file.txt” as the source, NOT the file “file.txt”

50 / 65 Writing Files  Use the PrintWriter class

51 / 65 Writing Files  Use the PrintWriter class  Constructors:  PrintWriter(File file):Creates a PrintWriter for the specified File  PrintWriter(String name):Creates a PrintWriter for the specified File with the name

52 / 65 The PrintWriter class  Methods:  void print(String) : Writes a String

53 / 65 The PrintWriter class  Methods:  void print(String) : Writes a String  void print(int) : Writes an int  void print(float) : Writes a float

54 / 65 The PrintWriter class  Methods:  void print(String) : Writes a String  void print(int) : Writes an int  void print(float) : Writes a float  void println(String) :Writes a String but also adds a line separator

55 / 65 The PrintWriter class  Methods:  void print(String) : Writes a String  void print(int) : Writes an int  void print(float) : Writes a float  void println(String) :Writes a String but also adds a line separator  void flush() :Flushes the output stream. Ensures writing to the file

56 / 65 The PrintWriter class  Methods:  void print(String) : Writes a String  void print(int) : Writes an int  void print(float) : Writes a float  void println(String) :Writes a String but also adds a line separator  void flush() :Flushes the output stream. Ensures writing to the file  void close() :Closes the output stream.

57 / 65 Writing Files PrintWriter output = null; try { output = new PrintWriter(new File(“test”)); // creates a file if it does not exist; // discards the current content if the file exists output.print("John T Smith "); output.println(90); output.print("Eric K Jones "); output.println(85); output.flush(); } catch(IOException ioe) { System.out.println(ioe.toString()); } finally { if (output != null) output.close(); }

58 / 65 Writing Files  Problem: What if you want to append to the file not replace it?

59 / 65 Writing Files  Problem: What if you want to append to the file not replace it?  Solution 1: Read the whole file, then write it back.

60 / 65 Writing Files  Problem: What if you want to append to the file not replace it?  Solution 1: Read the whole file, then write it back.  Cumbersome and too much work

61 / 65 Writing Files  Problem: What if you want to append to the file not replace it?  Solution 1: Read the whole file, then write it back.  Cumbersome and too much work  Solution 2: Use the FileWriter class

62 / 65 Writing Files  Problem: What if you want to append to the file not replace it?  Solution 1: Read the whole file, then write it back.  Cumbersome and too much work  Solution 2: Use the FileWriter class  FileWriter(File file, boolean append)

63 / 65 Writing Files  Problem: What if you want to append to the file not replace it?  Solution 1: Read the whole file, then write it back.  Cumbersome and too much work  Solution 2: Use the FileWriter class  FileWriter(File file, boolean append)  PrintWriter pw = new PrintWriter(new FileWriter(file, true) )

64 / 65 Writing Files PrintWriter output = null; try { output = new PrintWriter(new File(“test”)); // creates a file if it does not exist; // discards the current content if the file exists output.print("John T Smith "); output.println(90); output.print("Eric K Jones "); output.println(85); output.flush(); } catch(IOException ioe) { System.out.println(ioe.toString()); } finally { if (output != null) output.close(); }

65 / 65 Writing Files – Append PrintWriter output = null; try { output = new PrintWriter( new FileWriter(new File(“test”), true) ); // creates a file if it does not exist; // discards the current content if the file exists output.print("John T Smith "); output.println(90); output.print("Eric K Jones "); output.println(85); output.flush(); } catch(IOException ioe) { System.out.println(ioe.toString()); } finally { if (output != null) output.close(); }

66 / 65 Summary  Use Scanner for reading from command-line and files.  Based on delimiters  Use PrintWriter for writing to files