CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O



Similar documents
Object-Oriented Programming in Java

Using Files as Input/Output in Java 5.0 Applications

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

CS 121 Intro to Programming:Java - Lecture 11 Announcements

AP Computer Science Static Methods, Strings, User Input

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Basics of Java Programming Input and the Scanner class

Chapter 2: Elements of Java

Sample CSE8A midterm Multiple Choice (circle one)

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

13 File Output and Input

Introduction to Java

Building Java Programs

D06 PROGRAMMING with JAVA

Topic 11 Scanner object, conditional execution

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Comp 248 Introduction to Programming

Homework/Program #5 Solutions

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Visit us at

Building Java Programs

Chapter 2 Introduction to Java programming

Chapter 3. Input and output. 3.1 The System class

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Reading Input From A File

Introduction to Java. CS 3: Computer Programming in Java

Stream Classes and File I/O

Introduction to Programming

Event-Driven Programming

Course Intro Instructor Intro Java Intro, Continued

Building Java Programs

Files and input/output streams

Carron Shankland. Content. String manipula3on in Java The use of files in Java The use of the command line arguments References:

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

AP Computer Science Java Mr. Clausen Program 9A, 9B

AP Computer Science File Input with Scanner

Creating a Simple, Multithreaded Chat System with Java

6.1. Example: A Tip Calculator 6-1

JAVA ARRAY EXAMPLE PDF

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

Install Java Development Kit (JDK) 1.8

Division of Informatics, University of Edinburgh

Part I. Multiple Choice Questions (2 points each):

J a v a Quiz (Unit 3, Test 0 Practice)

CS 106 Introduction to Computer Science I

AP Computer Science Java Subset

JAVA.UTIL.SCANNER CLASS

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

CS 1302 Ch 19, Binary I/O

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

D06 PROGRAMMING with JAVA

CSE 8B Midterm Fall 2015

Quick Introduction to Java

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Building Java Programs

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Chapter 2 Elementary Programming

Week 1: Review of Java Programming Basics

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

Question R11.3. R11.3 How do you open a file whose name contains a backslash, like c:\temp\output.dat?

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Lecture J - Exceptions

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

Programming and Data Structures with Java and JUnit. Rick Mercer

public static void main(string[] args) { System.out.println("hello, world"); } }

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

What is an I/O Stream?

Assignment 4 Solutions

Explain the relationship between a class and an object. Which is general and which is specific?

Lesson: All About Sockets

Building a Multi-Threaded Web Server

WRITING DATA TO A BINARY FILE

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Software Development in Java

IMDB Data Set Topics: Parsing Input using Scanner class. Atul Prakash

CS 112/ Section 02 Hilal Ünal Aslıhan Ekim Merve Özkılınç Notes of March 11, 2008 and March 13, 2008: Pig Latin: add adday. main.

CS 106 Introduction to Computer Science I

The following program is aiming to extract from a simple text file an analysis of the content such as:

ECE 122. Engineering Problem Solving with Java

Chapter 10. A stream is an object that enables the flow of data between a program and some I/O device or file. File I/O

Java CPD (I) Frans Coenen Department of Computer Science

CS170 Lab 11 Abstract Data Types & Objects

Data Structures Lecture 1

Interactive Programs and Graphics in Java

Line-based file processing

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Transcription:

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O 1

Sending Output to a (Text) File import java.util.scanner; import java.io.*; public class TextFileOutputDemo1 public static void main(string[] args) throws IOException Scanner in = new Scanner(System.in); System.out.print( Enter your name: ); String name = in.nextline(); PrintWriter outputfile = new PrintWriter( out.txt ); outputfile.println(name); outputfile.close(); 2

Creating a File for Text Output We need a new class: PrintWriter To gain access to it we need to import it with: import java.io.*; To create and open the file: PrintWriter outfile = new PrintWriter(fileName); 3

Creating a File for Text Output We need a new class: PrintWriter To gain access to it we need to import it with: import java.io.*; To create and open the file: PrintWriter outfile = new PrintWriter(fileName); String 4

Writing Output to a Text File The PrintWriter class has output methods you are already familiar with: print println Instead of calling System.out.print(...) or System.out.println(...), you invoke: outfile.print(...) outfile.println(...) 5

Writing Output to a Text File The PrintWriter class has output methods you are already familiar with: print println Instead of calling System.out.print(...) or System.out.println(...), you invoke: outfile.print(...) outfile.println(...) PrintWriter object 6

Closing the File It is important to remember to explicitly close a file you are done writing to: outfile.close() 7

Closing the File It is important to remember to explicitly close a file you are done writing to: outfile.close() PrintWriter object 8

Your Turn Write a program that asks the user for a file name and then outputs the numbers 1 through 10, one per line, to the corresponding file. 9

Output Numbers import java.util.scanner; import java.io.*; public class OutputNumbers public static void main(string[] args) throws IOException Scanner in = new Scanner(System.in); System.out.print( Enter the file name: ); String filename = in.nextline(); PrintWriter outputfile = new PrintWriter(fileName); for (int i = 1; i <= 10; i++) outputfile.println(i); outputfile.close(); 10

What If an Error Occurs? What could go wrong when we try to create a file? We might not be able to create it! In that case an exception (error) is generated/raised by the program. What can we do about it? 11

Exceptions There are a variety of errors that can occur in a Java program that result in an exception being raised Java forces us to deal with some of them by either explicitly stating that such an exception might occur in our program or by catching the exception and dealing with it in our code 12

Stating That Exception Might Occur import java.util.scanner; import java.io.*; public class TextFileOutputDemo1 public static void main(string[] args) throws IOException Scanner in = new Scanner(System.in); System.out.print( Enter your name: ); String name = in.nextline(); PrintWriter outputfile = new PrintWriter( out.txt ); outputfile.println(name); outputfile.close(); 13

Dealing With Exception If It Occurs import java.util.scanner; import java.io.*; public class TextFileOutputDemo2 public static void main(string[] args) Scanner in = new Scanner(System.in); System.out.print( Enter your name: ); String name = in.nextline(); try PrintWriter outputfile = new PrintWriter( out.txt ); outputfile.println(name); outputfile.close(); catch (IOException e) System.out.println( Error opening the file out.txt ); 14

Try-Catch You can think of it as a control structure in that it affects the flow of execution of the program when an exception occurs. try // statements possibly raising exception catch (exception declaration) // statements dealing with exception 15

Reading Input from a (Text) File import java.util.scanner; import java.io.*; public class TextFileInputDemo1 public static void main(string[] args) throws IOException File file = new File("in.txt"); Scanner inputfile = new Scanner(file); String line = inputfile.nextline(); inputfile.close(); System.out.println(line); 16

Opening a File for Text Input We need a new class: File To gain access to it we need to import it with: import java.io.*; To open an existing file: File file = new File(fileName); Scanner infile = new Scanner(file); 17

Opening a File for Text Input We need a new class: File To gain access to it we need to import it with: import java.io.*; To open an existing file: File file = new File(fileName); Scanner infile = new Scanner(file); String 18

Reading Input from a Text File The Scanner class has input methods you are already familiar with: nextline, nextint, nextdouble, etc. Now we also need a way to check when we reach the end of the file: boolean hasnext() It takes no parameters and returns true if there is more data to read, and false otherwise 19

Closing the File It is important to remember to explicitly close a file you are done reading from: infile.close() 20

Closing the File It is important to remember to explicitly close a file you are done reading from: infile.close() Scanner object 21

Your Turn Complete the following program that asks the user for a file name, opens the file, reads one line at a time and outputs the line to the screen, until it reaches the end of the file. Make sure you catch the possible IOException in a try-catch statement. 22

Read File import java.util.scanner; import java.io.*; public class ReadFile public static void main(string[] args) Scanner in = new Scanner(System.in); System.out.print("Enter file name: "); String filename = in.nextline(); try File file = new File(fileName); Scanner inputfile = new Scanner(file); while (inputfile.hasnext()) String line = inputfile.nextline(); System.out.println(line); inputfile.close(); catch (IOException e) System.out.println( "There was a problem reading from " + filename); 23

Reading Non-String Values Method readline reads a line of input and returns it as a String What if we want to input integer or real values? We read them as strings with readline, and then convert the string value to the corresponding numeric value 24

Converting String Values There are useful methods to handle the conversion of a String value to the corresponding numeric value: int Integer.parseInt(String str) double Double.parseDouble(String str) For example: int i = Integer.parseInt( 1234 ); double d = Double.parseDouble( 3.1415 ); 25

Your Turn Write a program that asks the user for a file name, opens the file, reads a bunch of integer values, one per line, until it reaches the end of the file. The program computes and outputs the average of the integers to the screen. Make sure you catch the possible IOException in a try-catch statement. 26

Your Turn 27