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

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

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

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

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

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

Java Input/Output. 11 April 2013 OSU CSE 1

File Input and Output Review CSC 123 Fall 2018 Howard Rosenthal

PIC 20A Streams and I/O

Input from Files. Buffered Reader

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

IT101. File Input and Output

File I/O Array Basics For-each loop

CS 251 Intermediate Programming Java I/O Streams

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CN208 Introduction to Computer Programming

Dining philosophers (cont)

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

Chapter 4: Loops and Files

Chapter 4: Loops and Files

Object-Oriented Programming in Java

Unit 10: exception handling and file I/O

Input-Output and Exception Handling

CS Programming I: File Input / Output

Introduction Unit 4: Input, output and exceptions

CP122 CS I. Chapter 11: File I/O and Exceptions

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

CSC 1214: Object-Oriented Programming

CP122 CS I. Chapter 11: File I/O and Exceptions

HST 952. Computing for Biomedical Scientists Lecture 8

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003

CS Programming I: File Input / Output

Reading Input from Text File

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

1.00 Lecture 30. Sending information to a Java program

Today. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes. Debugging tools

Sorting/Searching and File I/O

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

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

Simple Java Input/Output

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

Streams and File I/O

File I/O and Exceptions

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

FILE I/O. CS302 Introduction to Programming University of Wisconsin Madison Lecture 27. By Matthew Bernstein

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

Darshan Institute of Engineering & Technology for Diploma Studies

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

Java file manipulations

Compile error. 2. A run time error occurs when the program runs and is caused by a number of reasons, such as dividing by zero.

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.

Objec&ves. Review. Standard Error Streams

Streams and File I/O

File IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Introductory Programming Exceptions and I/O: sections

CP122 CS I. Chapter 7: File I/O and Exceptions

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

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

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)

COMP-202 Unit 9: Exceptions

CMPSCI 187: Programming With Data Structures. Lecture #24: Files and a Case Study David Mix Barrington 2 November 2012

CS1092: Tutorial Sheet: No 3 Exceptions and Files. Tutor s Guide

11/1/2011. Chapter Goals

Overview CSE 143. Input and Output. Streams. Other Possible Kinds of Stream Converters. Stream after Stream... CSE143 Wi

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

Text User Interfaces. Keyboard IO plus

Computer Science is...

תוכנה 1 תרגול 8 קלט/פלט רובי בוים ומתי שמרת

Name: Checked: Preparation: Write the output of DeckOfCards.java to a text file Submit through Blackboard by 8:00am the morning of Lab.

CISC 323 (Week 9) Design of a Weather Program & Java File I/O

Data Structures. 03 Streams & File I/O

Recitation: Loop Jul 7, 2008

CS163/164 Final Exam Study Session

Principles of Computer Science I

COE 212 Engineering Programming. Welcome to Exam II Monday May 13, 2013

Input & Output in Java. Standard I/O Exception Handling

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

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

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

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

Lab 13. Name: Checked:

I/O STREAM (REQUIRED IN THE FINAL)

CS159 Midterm #1 Review

Dec. 16/ Deciding Which Loop to Use

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Au

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Sp

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

Name: Checked: Preparation: Investment Calculator with input and output to text files Submit through Blackboard by 8:00am the morning of Lab.

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Lecture 19 Programming Exceptions CSE11 Fall 2013

Happy Cinco de Mayo!!!!

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name: Question Value Score

File Operations in Java. File handling in java enables to read data from and write data to files

Lecture 11.1 I/O Streams

File Input/Output. Introduction to Computer Science I. Overview (1): Overview (2): CSE 1020 Summer Bill Kapralos. Bill Kapralos.

23 Error Handling What happens when a method is called? 23.1 What is Exception Handling? A.m() B.n() C.p()

Question 1. (2 points) What is the difference between a stream and a file?

Transcription:

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

I/O Streams A stream is a sequence of bytes that flow from a source to a destination In a program, we read information from an input stream and write information to an output stream A program can manage multiple streams at a time The java.io package contains many classes that allow us to define various streams with specific characteristics COMP 202 File Access 2

I/O Stream Categories The classes in the I/O package divide input and output streams into other categories An I/O stream is either a character stream, which deals with text data byte stream, which deal with byte data COMP 202 File Access 3

Standard I/O There are three standard I/O streams The System class contains three object reference variables (in, out, err) declared public and static (can be accessed via class name). System.in standard input (typically keyboard) we give System.in as input to Scanner constructor to read from keyboard System.out standard output (typically a window on screen) println is method of out output stream, thus to print ot standard output we call System.out.println COMP 202 File Access 4

The Standard Input Stream We ve used the standard input stream to create a Scanner object to process input read interactively from the user: Scanner scan = new Scanner (System.in); The Scanner object converts bytes from the stream into characters, and provides various methods to access those characters (by line, by word, by type, etc.) COMP 202 File Access 5

Reading Text Files We can read a text file sequentially using the file as the input stream for our scanner object: Assume you have a file test.txt Alternative 1: Construct a FileReader object and use that as input for the Scanner constructor FileReader reader = new FileReader( test.txt ); Scanner scan = new Scanner (reader); Alternative 2: Construct a File object and use that as input for the Scanner constructor Scanner scan = new Scanner (new File( test.txt ); You can then use the Scanner operators (next, nextline, nextint, )to read the file sequentially. All file related access must be enclosed in a try/catch block or the method must indicate that it can throw an IOException COMP 202 File Access 6

Line Numbering // reprint lines in input file and prefix them with line numbers import java.io.*; import java.util.scanner; public class LineNumberer { public static void main (String[] args) { int linenumber = 1; // line number initialized to 1 try { Scanner filescan = new Scanner (new File("test.txt")); // reprint every line with number prefixed while (filescan.hasnextline()){ System.out.println("/* " + linenumber++ + " */" + filescan.nextline()); // you must catch exception catch (IOException ex) { System.out.println("Error processing file: " + ex); COMP 202 File Access 7

Writing to a Text File To write output to a file, construct a PrintWrite object the given file name PrintWriter out = new PrintWriter( output.txt ); If the output file already exists, it is emptied before the new data is written into it (overwrite) if it doesn t exist, it will be created. Use the print and println methods to send numbers, objects an strings to a PrintWriter object out.print(29.95 + \t ); out.println( Hello World ); When you are done writing to a file close the corresponding PrintWriter. out.close(); COMP 202 File Access 8

Line Numberer 2: // reprint lines in input file and prefix them with line numbers import java.io.*; import java.util.scanner; public class LineNumberer2 { public static void main (String[] args) throws IOException { int counter = 1; // line number initialized to 1 String inputfile = "test.txt"; // default input String outputfile = "output.txt"; // default output int linenumber=0; // input and output could be given through command line if (args.length >= 1) inputfile = args[0]; if (args.length >= 2) outputfile = args[1]; Scanner filescan = new Scanner (new File(inputFile)); PrintWriter out = new PrintWriter(outputFile); // output every line with number prefixed while (filescan.hasnextline()){ out.println("/* " + linenumber++ + " */" + filescan.nextline()); // close the file out.close(); Find the differences to LineNumberer COMP 202 File Access 9

Processing structured text files Scanner The usual delimiter for next of Scanner class is other delimiters can be chosen (e.g., ; ) Writing to a file By using first a FileWriter (provides only minimum support to write to a file) and then a BufferedWriter (writes data to disk in chunks) and then a PrintWriter data is written in a more efficient way to the disk this will speed up your program if you write large amounts of data COMP 202 File Access 10

MyWord.java import java.util.scanner; import java.io.*; public class MyWorld { public static void main (String[] args) { final int MAX = 200; Country[] myworld = new Country[MAX]; String line, name, filename="countries.dat"; int count = 0; long population, area; try { Scanner filescan = new Scanner (new File(fileName)); while (filescan.hasnext()){ line = filescan.nextline(); Scanner linescan = new Scanner(line).useDelimiter(";"); try { name = linescan.next(); population = linescan.nextlong(); area = linescan.nextlong(); myworld[count++] = new Country (name, population, area); catch (Exception exception){ System.out.println ("Error in input. Line ignored:"); System.out.println (line); for (int i = 0; i < count; i++)system.out.println (myworld[i]); catch (FileNotFoundException exception){ System.out.println ("The file " + filename + " was not found."); COMP 202 File Access 11

Country.java public class Country { private String name; private long population; // number of people private long area; // geographical area public Country (String countryname, long numpeople, long size) { name = countryname; population = numpeople; area = size; public String tostring() { return name + ": " + population + " people on " + area + " sqkms is " + (population / area) + " people per sqkm"; public void addtofile(string filename) throws IOException { FileWriter fw = new FileWriter (filename,true); //true for appending BufferedWriter bw = new BufferedWriter (fw); PrintWriter outfile = new PrintWriter (bw); outfile.println (name + ";" + population + ";" + area); outfile.close(); COMP 202 File Access 12

Advanced Topics There are many other ways to read and write to files: random access: access arbitrary location of file directly contrast to sequential access read/write byte streams more compressed Object streams write out entire objects to a file read in an entire object from a file We do not discuss these andvanced topics in class but they are all very useful in specific situations. A good reference to study all kinds of IO http://java.sun.com/docs/books/tutorial/essential/io/ COMP 202 File Access 13

When to use files In any application that requires information to exist for a long time: Experimental data Music Databases Computer memory is volatile, meaning that once the computer is shut off the information is gone. Information stored in files can remain available even after the computer is turned off. COMP 202 File Access 14

Designing For Files Exception Checking Input validation checking Hardware problems checking No floppy disk or storage device present Sector error on diskette or device Input Process Save Methodology Get input from user Validate user input Save it to a file COMP 202 File Access 15