Data stored in variables and arrays is temporary

Similar documents
Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

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

Lecture 7. File Processing

Java Input/Output. 11 April 2013 OSU CSE 1

File. Long term storage of large amounts of data Persistent data exists after termination of program Files stored on secondary storage devices

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

CS 251 Intermediate Programming Java I/O Streams

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

Reading Input from Text File

HST 952. Computing for Biomedical Scientists Lecture 8

CN208 Introduction to Computer Programming

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

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

Chapter 12. File Input and Output. CS180-Recitation

Java Programming Lecture 9

Data Structures. 03 Streams & File I/O

Previous to Chapter 7 Files

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

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

CS 200 File Input and Output Jim Williams, PhD

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.

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

1.00 Lecture 30. Sending information to a Java program

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

Software 1 with Java. Recitation No. 9 (Java IO) December 10,

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

Midterm Examination (MTA)

Java file manipulations

Introduction to Computer Science Unit 2. Notes

IT101. File Input and Output

Chapter 4 Java I/O. X i a n g Z h a n g j a v a c o s q q. c o m

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

Software 1 with Java. Recitation No. 7 (Java IO) May 29,

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

Simple File Input And Output

Darshan Institute of Engineering & Technology for Diploma Studies

Software 1. Java I/O

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

Streams and File I/O

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

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

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

Programming with Java

Files and IO, Streams. JAVA Standard Edition

Welcome1.java // Fig. 2.1: Welcome1.java // Text-printing program.

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

Introduction to Computer Science Unit 2. Notes

Exceptions and Working with Files

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.

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

Tirgul 1. Course Guidelines. Packages. Special requests. Inner classes. Inner classes - Example & Syntax

Text User Interfaces. Keyboard IO plus

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

CS 161: Object Oriented Problem Solving

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

Simple File Input And Output

Chapter 12. Files (reference: Deitel s chap 11) chap8

WOSO Source Code (Java)

1.00 Lecture 31. Streams 2. Reading for next time: Big Java , The 3 Flavors of Streams

Example: Copying the contents of a file

Job Migration. Job Migration

CS Week 11. Jim Williams, PhD

CS 211: Existing Classes in the Java Library

Exceptions Binary files Sequential/Random access Serializing objects

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

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

String temp [] = {"a", "b", "c"}; where temp[] is String array.

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

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

CS141 Programming Assignment #6

Chapter 10. IO Streams

Streams and File I/O

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

Chapter 17 Binary I/O. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.

Streams and File I/O

1.00/ Introduction to Computers and Engineering Problem Solving. Final Exam / December 21, 2005

FILE I/O IN JAVA. Prof. Chris Jermaine

Arrays & Classes. Problem Statement and Specifications

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Introduction to Classes and Objects

CSCI 1103: File I/O, Scanner, PrintWriter

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide

School of Informatics, University of Edinburgh

7 Streams and files. Overview. Binary data vs text. Binary data vs text. Readers, writers, byte streams. input-output

Sorting/Searching and File I/O

What is Serialization?

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

Here is a hierarchy of classes to deal with Input and Output streams.

Unit 10: exception handling and file I/O

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

AP Computer Science Unit 1. Programs

Streams and File I/O

Assignment 8B SOLUTIONS

Objec&ves. Review. Standard Error Streams

Building Java Programs

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

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

CSCI 1103: File I/O, Scanner, PrintWriter

CS 161: Object Oriented Problem Solving

Transcription:

Data stored in variables and arrays is temporary It s lost when a local variable goes out of scope or when the program terminates For long-term retention of data, computers use files. Computers store files on secondary storage devices hard disks, optical disks, flash drives and magnetic tapes. Data maintained in files is persistent data because it exists beyond the duration of program execution.

Java views each file as a sequential stream of bytes (Fig. 8.1). Every operating system provides a mechanism to determine the end of a file, such as an end-of-file marker or a count of the total bytes in the file that is recorded in a system-maintained administrative data structure. A Java program simply receives an indication from the operating system when it reaches the end of the stream

Fig. 8.1 Java s view of a file of n bytes.

File streams can be used to input and output data as bytes or characters. Streams that input and output bytes are known as bytebased streams, representing data in its binary format. Streams that input and output characters are known as character-based streams, representing data as a sequence of characters. Files that are created using byte-based streams are referred to as binary files. Files created using character-based streams are referred to as text files. Text files can be read by text editors. Binary files are read by programs that understand the specific content of the file and the ordering of that content.

A Java program opens a file by creating an object and associating a stream of bytes or characters with it. Can also associate streams with different devices. Java creates three stream objects when a program begins executing System.in (the standard input stream object) normally inputs bytes from the keyboard System.out (the standard output stream object) normally outputs character data to the screen System.err (the standard error stream object) normally outputs character-based error messages to the screen. Class System provides methods setin, setout and seterr to redirect the standard input, output and error streams, respectively.

Java programs perform file processing by using classes from package java.io. Includes definitions for stream classes FileInputStream (for byte-based input from a file) FileOutputStream (for byte-based output to a file) FileReader (for character-based input from a file) FileWriter (for character-based output to a file) You open a file by creating an object of one these stream classes. The object s constructor opens the file.

Can perform input and output of objects or variables of primitive data types without having to worry about the details of converting such values to byte format. To perform such input and output, objects of classes ObjectInputStream and ObjectOutputStream can be used together with the byte-based file stream classes FileInputStream and FileOutputStream.

Class File provides information about files and directories. Character-based input and output can be performed with classes Scanner and Formatter. Class Scanner is used extensively to input data from the keyboard. This class can also read data from a file. Class Formatter enables formatted data to be output to any text-based stream in a manner similar to method System.out.printf.

Class File provides four constructors. The one with a String argument specifies the name of a file or directory to associate with the File object. The name can contain path information as well as a file or directory name. A file or directory s path specifies its location on disk. An absolute path contains all the directories, starting with the root directory, that lead to a specific file or directory. A relative path normally starts from the directory in which the application began executing and is therefore relative to the current directory.

8.3 Class File (cont.) Figure 8.2 lists some common File methods. Fig. 8.2 File methods.

Fig. 8.2 File methods.

import import import import java.io.file; java.io.ioexception; java.util.date; java.util.scanner; /** * * File class used to Obtain file and directory information. */ public class FileDemonstration { public static void main( String[] args) throws IOException { Scanner input = new Scanner (System.in); System.out.print("Enter file or directory name: "); analyzepath(input.nextline()); Fig. 8.3 File class used to obtain file and directory information.

public static void analyzepath (String path) { // create File object based on user input. File name = new File( path ); if ( name.exists()) { System.out.println( name.getname()+" exists"); if (name.isfile()) { System.out.println("is a file"); System.out.printf("%s\n",name.isAbsolute()? "is absolute path":"is not absolute path"); Date dt = new Date(name.lastModified()); // milliseconds to date and time. System.out.println("Last modified at: " + dt); System.out.println("Length: "+name.length()); // in bytes System.out.println("Path: "+name.getpath()); System.out.println("Absolute path: "+name.getabsolutepath()); System.out.println("Parent: "+name.getparent()); System.out.printf("%s%s\n", name,name.delete()?" is deleted": "is not deleted"); if (name.isdirectory()) { System.out.println("is a directory"); System.out.println("\nDirectory contents:"); String[] list = name.list(); for (int i=0; i<list.length; i++) System.out.println(list[i]); else System.out.printf("%s %s\n", path, "does not exist."); // end class

Enter file or directory name: E:\hikmat\research\report.docx report.docx exists is a file output is absolute path Last modified at: Sat Aug 31 13:36:31 EEST 2013 Length: 174562 Path: E:\hikmat\research\report.docx Absolute path: E:\hikmat\research\report.docx Parent: E:\hikmat\research E:\hikmat\research\report.docx is deleted ---------------------------------------------------------------------------------------------------------------------------------------------------------Enter file or directory name: C:\users\public public exists another is a directory Directory contents: Book Place Desktop Documents Downloads Favorites Libraries Music Pictures Recorded TV TEMP Videos output

Sequential-access files store records in order by the record-key field. Text files are human-readable files.

Java imposes no structure on a file Notions such as records do not exist as part of the Java language. You must structure files to meet the requirements of your applications.

// Account class to keep record of one client. import java.io.serializable; class Account implements Serializable { private int number; private String firstname, lastname; private double balance; public Account() { this(0, "", "", 0.0); public Account(int acct, String first, String last, double bal) { setnumber(acct); setfirstname(first); setlastname(last); setbalance(bal); public void setnumber(int num) { number = num; public int getnumber() { return number; public void setfirstname(string first) { firstname = first; public String getfirstname() { return firstname; public void setlastname(string last) { lastname = last; public String getlastname() { return lastname; public void setbalance(double bal) { balance = bal; public double getbalance() { return balance; Fig. 8.4 Account class maintains information for one account.

Formatter outputs formatted Strings to the specified stream. The constructor with one String argument receives the name of the file, including its path. If a path is not specified, the JVM assumes that the file is in the directory from which the program was executed. If the file does not exist, it will be created. If an existing file is opened, its contents are truncated. Solution: use FileWriter with Formatter, example: FileWriter filewriter = new FileWriter ("D:\\userprofile.txt", true); Formatter formatter = new Formatter (filewriter);

// Creating a sequential text file "clients.txt" using formatter. import java.io.filenotfoundexception; import java.util.formatter; import java.util.scanner; public class CreateTextFile { private Formatter output; // object used to output text to file. public void openfile() throws FileNotFoundException output = new Formatter("e:\\clients.txt"); public void addrecords() { Account record = new Account(); Scanner input = new Scanner(System.in); { System.out.println("To terminate, press a non-numeric character"); System.out.print("Enter account number, first name, last name, balance: \n? "); while(input.hasnextint() { record.setnumber(input.nextint()); record.setfirstname(input.next()); record.setlastname(input.next()); record.setbalance(input.nextdouble()); output.format("%-8d %-10s %-10s %-10.2f\r\n", record.getnumber(), record.getfirstname(), record.getlastname(), record.getbalance()); System.out.print("Enter account number, first name, last name, balance: \n? "); public void closefile() { output.close(); Fig. 8.5 Writing data to a sequential text file with class formatter.

class CreateTextFileTest { public static void main(string[] args) throws FileNotFoundException { CreateTextFile application = new CreateTextFile(); application.openfile(); application.addrecords(); application.closefile(); Fig. 8.6 Testing the CreateTextFile class. To terminate, press a non-numeric Enter account number, first name,? 101 Mohammad Jaber 7340.71 Enter account number, first name,? 103 Ahmad Ali 5090.5 Enter account number, first name,? 104 Yousef Saleh 12761 Enter account number, first name,? z 101 103 104 Mohammad Ahmad Yousef Jaber Ali Saleh character last name, balance: output last name, balance: last name, balance: last name, balance: 7340.71 5090.50 12761.00 clients.txt Sample data

The application in Figs. 8.7 and 8.8 reads records from the file "clients.txt" created by the application of Section 8.4.1 and displays the record contents.

import java.io.file; import java.io.filenotfoundexception; import java.util.scanner; // Reading a sequential text file "clients.txt" using Scanner. public class ReadTextFile { private Scanner input; public void openfile() throws FileNotFoundException { input = new Scanner (new File("e:\\clients.txt")); public void readrecords() { System.out.printf("%-10s\t%-10s\t%-10s\t%-10s\r\n", "Account","First Name","Last Name","Balance"); System.out.printf("%-10s\t%-10s\t%-10s\t%-10s\r\n", "-------","----------","---------","-------"); while (input.hasnext()) { System.out.printf("%-10d\t%-10s\t%-10s\t%-10.2f\r\n", input.nextint(), input.next(), input.next(), input.nextdouble()); public void closefile() { input.close(); Fig. 8.7 Sequential file reading using Scanner.

class ReadTextFileTest { public static void main(string[] args) throws FileNotFoundException { ReadTextFile application = new ReadTextFile(); application.openfile(); application.readrecords(); application.closefile(); Account ------101 103 104 Fig. 8.8 First Name ---------Mohammad Ahmad Yousef Testing the ReadTextFile class. Last Name --------Jaber Ali Saleh Balance ------7340.71 5090.50 12761.00 output

To retrieve data sequentially from a file, programs start from the beginning of the file and read all the data consecutively until the desired information is found. It might be necessary to process the file sequentially several times (from the beginning of the file) during the execution of a program. Class Scanner does not allow repositioning to the beginning of the file. The program must close the file and reopen it. Homework Write a program to inquire from the file "clients.txt about the zero balances, credit balances, and debit balances.

The data in many sequential files cannot be modified without the risk of destroying other data in the file. If the name Ali needed to be changed to Mohammad the old name cannot simply be overwritten, because the new name requires more space. Fields in a text file and hence records can vary in size. Records in a sequential-access file are not usually updated in place. Instead, the entire file is usually rewritten. Rewriting the entire file is uneconomical to update just one record, but reasonable if a substantial number of records need to be updated.