Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. File Input and Output

Similar documents
Reading Input from Text File

A token is a sequence of characters not including any whitespace.

CSCI 1103: File I/O, Scanner, PrintWriter

File Input and Output Review CSC 123 Fall 2018 Howard Rosenthal

Building Java Programs

File I/O Introduction to File I/O Text Files The File Class Binary Files 614

COMP-202: Foundations of Programming. Lecture 22: File I/O Jackie Cheung, Winter 2015

Object-Oriented Programming in Java

CSCI 1103: File I/O, Scanner, PrintWriter

File I/O Array Basics For-each loop

CS Programming I: File Input / Output

CS Programming I: File Input / Output

When we reach the line "z = x / y" the program crashes with the message:

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP File Access 1

Building Java Programs

Excep&ons and file I/O

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG

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

Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.

Agenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction

CIS 110: Introduction to Computer Programming

AP Computer Science. File Input with Scanner. Copyright 2010 by Pearson Education

COMP200 INPUT/OUTPUT. OOP using Java, based on slides by Shayan Javed

I/O Streams. COMP 202 File Access. Standard I/O. I/O Stream Categories

CS244 Advanced Programming Applications

EXCEPTIONS. Fundamentals of Computer Science I

Unit 10: exception handling and file I/O

Computer Science is...

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP 202 File Access 1

Text User Interfaces. Keyboard IO plus

COMP-202: Foundations of Programming. Lecture 12: Linked List, and File I/O Sandeep Manjanna, Summer 2015

Chapter 4: Loops and Files

CS 211: Existing Classes in the Java Library

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

File class in Java. Scanner reminder. File methods 10/28/14. File Input and Output (Savitch, Chapter 10)

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Testing and Debugging

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Arrays

Program 12 - Spring 2018

First Java Program - Output to the Screen

CSci 1103 Final. Name: Student ID:

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

Chapter 4: Loops and Files

Chapter 4 Classes in the Java Class Libraries

11/1/2011. Chapter Goals

Building Java Programs

Java Input/Output. 11 April 2013 OSU CSE 1

Starting Out with Java: From Control Structures Through Objects Sixth Edition

CS159. Nathan Sprague

Loops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Reading Text Files. 1 Reading from text files: Scanner

CS 302: Introduction to Programming in Java. Lectures 17&18. It s insanely hot. People desperately need some snowflakes

Mandatory Assignment 1, INF 4130, 2017

ing execution. That way, new results can be computed each time the Class The Scanner

Files & Exception Handling. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Simple Java Input/Output

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Methods

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

Exception Handling. CSE 114, Computer Science 1 Stony Brook University

Advanced Java Concept Unit 1. Mostly Review

Programming with Java

Building Java Programs

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

More on Java. Object-Oriented Programming

Fundamentals of Programming Data Types & Methods

COMP-202 Unit 9: Exceptions

AP Computer Science Unit 1. Programs

Lecture 8 " INPUT " Instructor: Craig Duckett

CSC 1214: Object-Oriented Programming

Input. Scanner keyboard = new Scanner(System.in); String name;

DPCompSci.Java.1718.notebook April 29, 2018

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

A+ Computer Science -

Files. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Computational Expression

Exceptions. Examples of code which shows the syntax and all that

COMP102: Test 1 Model Solutions

Intermediate Programming. Streams

CS159. Nathan Sprague

AP Computer Science Unit 1. Writing Programs Using BlueJ

COMP 202 Java in one week

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Object Oriented Programming. Java-Lecture 1

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements

Files. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Final Exam. CSC 121 Fall Lecturer: Howard Rosenthal. Dec. 13, 2017

Programming II (CS300)

Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

File I/O and Exceptions

double float char In a method: final typename variablename = expression ;

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Intro to Computer Science II

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

Adam Blank Lecture 2 Winter 2019 CS 2. Introduction to Programming Methods

Lecture Set 2: Starting Java

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

Final Exam. CSC 121 Fall Lecturer: Howard Rosenthal. Dec. 13, 2017

CS 251 Intermediate Programming Java I/O Streams

Building Java Programs Chapter 6

Transcription:

WIT COMP1000 File Input and Output

I/O I/O stands for Input/Output So far, we've used a Scanner object based on System.in for all input (from the user's keyboard) and System.out for all output (to the user's screen) System.in and System.out are predefined I/O objects that are available automatically in every Java program WIT COMP1000 2

WIT COMP1000 3 File I/O Files can also be used for input (to get data from a file into a program) and output (to put data into a file from a program) Files store data that need to be available after the program ends» All values in memory or displayed on the screen will be lost when the program terminates Files might store large data sets for input into a program, to save the need to type in all the data values individually

File Objects In Java, files on your computer are represented with File objects» Part of the java.io package that must be imported New File objects are created for each file that you want to read from or write to For example: File f = new File("test.txt"); There are many methods you can use with File objects, but we are going to focus on how to use them for input and output WIT COMP1000 4

File Input Reading from a file is done with a Scanner object, the same as we've been doing for keyboard input When you create a Scanner for file input, use the File object instead of System.in Example: File f = new File("test.txt"); Scanner fin = new Scanner(f); Or, these can be combined into a single statement: Scanner fin = new Scanner(new File("test.txt")); WIT COMP1000 5

FileNotFoundException When you create the Scanner with a File object, Java will open that file for reading If the file doesn't exist, a FileNotFoundException will be thrown You must use try/catch to check for and handle that exception» Or declare that the method containing the Scanner will throw the exception» Be sure to handle it somewhere in your program WIT COMP1000 6

Closing Files When the file is no longer needed in the program, it's important that the file is closed» Otherwise unexpected program termination might result in data corruption in the file There are several ways to handle closing files Newer versions of Java support a convenient mechanism to automatically close files» Based on try blocks» Called try-with-resource WIT COMP1000 7

Example: File-based Scanner import java.io.file; import java.io.filenotfoundexception; import java.util.scanner; Adding the Scanner creation here will cause it to be automatically closed after the try/catch block public class ClassExamples { public static void main(string[] args) { try (Scanner fin = new Scanner(new File("test.txt"))) { // process the file here catch (FileNotFoundException ex) { System.out.println("File test.txt not found!"); System.exit(0); WIT COMP1000 8

Files in Eclipse You can add files to your Eclipse project directly Right-click on the project (in Package Explorer), go to New, and Select File Give the file a name (e.g., test.txt) The file will show up under the project heading and you will be able to access it directly in your programs in that project» Otherwise you have to specify the path to where the file lives on your hard drive relative to the project directory» By default, the file will be located in the project directory WIT COMP1000 9

File Paths The argument you use when creating the File object is a path to where that file lives on your computer Opening a file that is not in the main project directory requires you to specify the path to the file, including the name of the file For example, assuming that you put your Eclipse workspace in the default location, you would use something like this to open a file named test.txt on your Desktop: File f = new File("../../Desktop/test.txt"); The ".." values mean to go "up" directories towards the C:\ directory in Windows or the root (/) directory in Linux/OS X So, from the Eclipse project directory, go up to the main Eclipse workspace directory, then up to your main user directory, and then down into the Desktop directory WIT COMP1000 10

WIT COMP1000 11 Reading from a File Once the file is opened via a Scanner object, read from it the same way that you do with any Scanner» Using the nextint(), nextdouble(), nextline(), and next() methods You will still need to catch InputMismatchException when calling nextint() and nextdouble() The try block will automatically close the file at the end of the block (before catching exceptions)

Example: File Reading import java.io.file; import java.io.filenotfoundexception; import java.util.scanner; public class ClassExamples { public static void main(string[] args) { try (Scanner fin = new Scanner(new File("test.txt"))) { String firstline = fin.nextline(); String secondline = fin.nextline(); System.out.println(firstLine); System.out.println(secondLine); catch (FileNotFoundException ex) { System.out.println("File test.txt not found!"); System.exit(0); WIT COMP1000 12

Exercise Write a program that opens a file named integers.txt, then reads 5 integers from the file and prints each one out You will have to create the integers.txt file manually first and put at least 5 integers into it WIT COMP1000 13

Answer import java.io.file; import java.io.filenotfoundexception; import java.util.scanner; public class ClassExamples { public static void main(string[] args) { try (Scanner fin = new Scanner(new File("integers.txt"))) { for (int i = 1; i <= 5; i++) { int nextint = fin.nextint(); System.out.println(nextInt); catch (FileNotFoundException ex) { System.out.println("File integers.txt not found!"); System.exit(0); WIT COMP1000 14

NoSuchElementException If you try to read a value that isn't there then a NoSuchElementException will be thrown» For example, because you have already read all the way through the file and there are no values left in the file You can catch this exception as normal Or you can use the hasnextint(), hasnextdouble(), hasnextline(), and/or hasnext() methods to check if there is another value left in the file BEFORE you do the read» These work particularly well in a loop that will read every value out of a file WIT COMP1000 15

Example: Reading Every Line import java.io.file; import java.io.filenotfoundexception; import java.util.scanner; public class ClassExamples { public static void main(string[] args) { try (Scanner fin = new Scanner(new File("test.txt"))) { while (fin.hasnextline()) { String nextline = fin.nextline(); System.out.println(nextLine); catch (FileNotFoundException ex) { System.out.println("File test.txt not found!"); System.exit(0); WIT COMP1000 16

Writing to Files A Scanner can only read values out of a file Use a PrintWriter object to write value into a file Example: File f = new File("testOut.txt"); PrintWriter fout = new PrintWriter(f); Or the two can be combined into a single statement: PrintWriter fout = new PrintWriter(new File("testOut.txt")); Creating a PrintWriter object will automatically create the file if it doesn't already exist and will remove all existing data in the file if it does exist The file will show up in Eclipse under the project entry (might have to refresh the project view) WIT COMP1000 17

WIT COMP1000 18 Using a PrintWriter Creating a new PrintWriter might throw a FileNotFoundException» You either catch it or declare that your method throws it You can use the print(), printf(), and println() methods on a PrintWriter object» The same as with System.out Use the same modified try block to ensure that the PrintWriter will be closed as soon as it is done being used

Example: Writing to a File import java.io.file; import java.io.filenotfoundexception; import java.io.printwriter; public class ClassExamples { public static void main(string[] args) { try (PrintWriter fout = new PrintWriter(new File("testOut.txt"))) { double value = 42.42; fout.println("hello File World!"); fout.print("value: "); fout.printf("%.2f%n", value); catch (FileNotFoundException ex) { System.out.println("File testout.txt not found!"); System.exit(0); WIT COMP1000 19

Exercise Write a program that writes the numbers from 1 to 100 to a file named "numbers.txt" WIT COMP1000 20

Answer import java.io.file; import java.io.filenotfoundexception; import java.io.printwriter; public class ClassExamples { public static void main(string[] args) { try (PrintWriter fout = new PrintWriter(new File("numbers.txt"))) { for (int i = 1; i <= 100; i++) { fout.println(i); catch (FileNotFoundException ex) { System.out.println("File numbers.txt not found!"); System.exit(0); WIT COMP1000 21

Exercise Write a program that reads all the numbers from a file named "numbers.txt" and prints out (to the screen) any odd values found WIT COMP1000 22

Answer import java.io.file; import java.io.filenotfoundexception; import java.util.scanner; public class ClassExamples { public static void main(string[] args) { try (Scanner fin = new Scanner(new File("numbers.txt"))) { while (fin.hasnextint()) { int next = fin.nextint(); if (next % 2 == 1) { System.out.println(next); catch (FileNotFoundException ex) { System.out.println("File numbers.txt not found!"); System.exit(0); WIT COMP1000 23

Reading and Writing A single program can both read from one file and write to another file» That is, a program may have both Scanner objects based on files and PrintWriter objects In general you should never create a Scanner and a PrintWriter that are pointing at the same File object» It can be done, but it requires special care» Never do it in this course WIT COMP1000 24

Example: Reading and Writing import java.io.file; import java.io.filenotfoundexception; import java.io.printwriter; import java.util.scanner; public class ClassExamples { public static void main(string[] args) { try ( Scanner fin = new Scanner(new File("numbers.txt")); PrintWriter fout = new PrintWriter(new File("odds.txt")); ) { while (fin.hasnextint()) { int next = fin.nextint(); if (next % 2 == 1) { fout.println(next); catch (FileNotFoundException ex) { System.out.println("File not found!"); System.exit(0); WIT COMP1000 25

Using Multiple Files with try In the previous example, two files (one for input and one for output) need to be opened simultaneously Put both the Scanner and PrintWriter creation inside the parentheses after the try You must put a semicolon after each statement» Except the last, but it doesn't hurt to add a semicolon after the last statement too WIT COMP1000 26

Exercise Write a program that reads every line (one entire line at a time) from a file named "jedicode.txt". For each line, print both to the screen and to another file named "linecounts.txt" how many characters were on that line. Note that you'll need to create the jedicode.txt file yourself before you run the program. WIT COMP1000 27

Answer import java.io.file; import java.io.filenotfoundexception; import java.io.printwriter; import java.util.scanner; public class ClassExamples { public static void main(string[] args) { try ( Scanner fin = new Scanner(new File("jediCode.txt")); PrintWriter fout = new PrintWriter(new File("lineCounts.txt")); ) { while (fin.hasnextline()) { String nextline = fin.nextline(); System.out.println(nextLine.length()); fout.println(nextline.length()); catch (FileNotFoundException ex) { System.out.printf("File not found: %s%n", ex.getmessage()); System.exit(0); WIT COMP1000 28

File Names as Input The File object is created by giving it a file name, which is a String The argument does not have to be hard coded (e.g., "jedicode.txt") It can be a String variable, which can be read from the user via the normal System.in Scanner» Or another file, or anywhere else for that matter WIT COMP1000 29

Example: File Name from User import java.io.file; import java.io.filenotfoundexception; import java.io.printwriter; import java.util.scanner; public class ClassExamples { public static void main(string[] args) { Scanner keyboardinput = new Scanner(System.in); String outputfilename; System.out.print("Enter the output file name: "); outputfilename = keyboardinput.next(); try (PrintWriter fout = new PrintWriter(new File(outputFileName))) { for (int i = 1; i <= 1000; i++) { fout.println(i*i*i); catch (FileNotFoundException ex) { System.out.println("File " + outputfilename + " not found!"); System.exit(0); WIT COMP1000 30

Scanner and PrintWriter as Method Parameters We've already seen that you can pass a Scanner object as an argument into a method The same is true for PrintWriter objects If you use any Scanner or PrintWriter methods that might throw an exception, be sure to either catch them in the method where you call those methods or declare that your method throws those exceptions WIT COMP1000 31

Example: PrintWriter Parameter import java.io.file; import java.io.filenotfoundexception; import java.io.printwriter; public class ClassExamples { public static void main(string[] args) { try (PrintWriter fout = new PrintWriter(new File("testOut.txt"))) { outputnumbers(fout, 10, 99); catch (FileNotFoundException ex) { System.out.println("File testout.txt not found!"); System.exit(0); public static void outputnumbers(printwriter output, int start, int stop) { int count = 1; for (int i = start; i <= stop; i++, count++) { if(count % 10 == 0) { output.println(i); else { output.print(i + " "); WIT COMP1000 32

Exercise Write a program that copies the contents of one file into another file. In particular, ask the user for the names of both the original (input) file and the new (output) file. Write a method that is passed the already created Scanner and PrintWriter objects to do all of the copying (reading and writing). WIT COMP1000 33

Answer import java.io.file; import java.io.filenotfoundexception; import java.io.printwriter; import java.util.scanner; public class ClassExamples { public static void main(string[] args) { Scanner keyboardinput = new Scanner(System.in); System.out.print("Enter the input file name: "); String inputfilename = keyboardinput.next(); System.out.print("Enter the output file name: "); String outputfilename = keyboardinput.next(); try ( Scanner fin = new Scanner(new File(inputFileName)); PrintWriter fout = new PrintWriter(new File(outputFileName)); ) { copyfile(fin, fout); catch (FileNotFoundException ex) { System.out.println("File not found!"); System.exit(0); public static void copyfile(scanner original, PrintWriter copy) { while(original.hasnextline()) { String line = original.nextline(); copy.println(line); WIT COMP1000 34

File I/O Summary You can read from and write to files just like getting input and output with System.in and System.out Use a File object to represent a file in your program Use a Scanner with a File to read from the file» Use the next() methods to read values and hasnext() methods to check for more values Use a PrintWriter with a File to write to the file» Use the print() methods to write values Use the try-with-resource syntax to automatically close the Scanner or PrintWriter when done WIT COMP1000 35