Random Access Files Sandeep Patel. Random Access Files Random access files are files in which records can be accessed in any order –Also called direct.

Slides:



Advertisements
Similar presentations
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Advertisements

1 Streams and Input/Output Files Part 3. 2 Handling Primitive Data Types The basic input and output streams provide read/write methods that can be used.
1 Streams and Input/Output Files Part I. 2 Introduction So far we have used variables and arrays for storing data inside the programs. This approach poses.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
Files Files are used to store long term data. –Typically referred to as persistent data. –A file is a group of related records. –A list of friends addresses.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
Lecture 7 File I/O (and a little bit about exceptions)‏
17 File Processing. OBJECTIVES In this chapter you will learn:  To create, read, write and update files.  Sequential file processing.  Random-access.
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.
CIS 234: More File Input & Output Dr. Ralph D. Westfall May, 2007.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 18 Binary I/O.
© The McGraw-Hill Companies, 2006 Working with files Chapter 20.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
13.1 Understanding Files The File class Objects can read and write to the file system Use the File class to hold information about files and directories.
Chapter 20 – Streams and Binary Input/Output Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
Java Bits CS Data versus Information Bits are just bits (no inherent meaning) -conventions define relationship between bits and numbers -given a.
CS203 Programming with Data Structures Input and Output California State University, Los Angeles.
CSC – Java Programming II Lecture 9 January 30, 2002.
Files and Streams. Java I/O File I/O I/O streams provide data input/output solutions to the programs. A stream can represent many different kinds of sources.
1 Chapter 11 – Files and Streams 1 Introduction What are files? –Long-term storage of large amounts of data –Persistent data exists after termination of.
Input / Output Chapter 13.  We use files all the time  Programs are files  Documents are files  We want them to be “permanent”  To last beyond execution.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
CSC 213 – Large Scale Programming. Project #1 Recap.
Files and Streams. Midterm exam Time: Wednesday, October 31, 2007 Format: Multiple choices (about 15 to 20 questions) Determine the results of the code.
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.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
Binary Files, Random Access Files Binary Files The way data is stored in memory is sometimes called the raw binary format. Data can be stored in.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
Applications Development Input and Output in Java Topics covered: Some input-output capabilities of Java Example input code Java.
Introduction to Programming G50PRO University of Nottingham Unit 11 : Files Input/Ouput Paul Tennent
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 13 File Input and.
CHAPTER 15 STREAMS. CHAPTER GOALS To be able to read and write files To become familiar with the concepts of text and binary files To be able to read.
A stream is a sequence of data. A stream is a flowing sequence of characters.
Array Objectives To understand the concept of arrays To understand the purpose to which we use arrays. To be able to declare references to arrays. To be.
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.
PROG Mobile Java Application Development PROG Mobile Java Application Development Data Storage, Continued.
1 Chapter 19 Binary I/O. 2 Motivations F Data stored in a text file – is represented in human-readable form –Text file –Readable –Java source programs.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
 Learn about computer files  Use the Path class  Learn about  Streams  Buffers  file organization  Use Java’s IO classes to write to and read from.
1 CSC241: Object Oriented Programming Lecture No 32.
Learners Support Publications Working with Files.
Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that.
A data type in a programming language is a set of data with values having predefined characteristics.data The language usually specifies:  the range.
CSI 3125, Preliminaries, page 1 Files. CSI 3125, Preliminaries, page 2 Reading and Writing Files Java provides a number of classes and methods that allow.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
Java Programming, Second Edition Chapter Sixteen File Input and Output.
Python focus – files The open keyword returns a file object Opening a file myFile = open('C:\file.txt', arg) Optional argument The second argument controls.
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.
Object Oriented Programming Lecture 2: BallWorld.
Java IO Exploring the java.io package and living to talk about it.
CHAPTER 3 File Output.
IO in java.
Introduction to programming in java
Testing and Exceptions
MSIS 670: Object-Oriented Software Engineering
An Introduction to Java – Part I, language basics
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
CS 240 – Advanced Programming Concepts
OO Java Programming Input Output.
David Davenport Spring 2005
Presentation transcript:

Random Access Files Sandeep Patel

Random Access Files Random access files are files in which records can be accessed in any order –Also called direct access files –More efficient than sequential access files

Need for Random Access Files Real-time applications require immediate response –Example: respond to customer query about a bill –Sequencing through records for account is time- intensive Random (immediate) access meets real-time need –Directly read from or write to desired record

Example Consider the zip format. A ZIP archive contains files and is typically compressed to save space. It also contain a directory entry at the end that indicates where the various files contained within the ZIP archive begin

Accessing a specific file using sequential access Open the ZIP archive. Search through the ZIP archive until you locate the file you want to extract. Extract the file. Close the ZIP archive. On an average, we have to read half of the zip archive to find the required file

Accessing a specific file using random access Open the ZIP archive. Seek to the directory entry and locate the entry for the file you want to extract from the ZIP archive. Seek (backward) within the ZIP archive to the position of the file to extract. Extract the file. Close the ZIP archive. This is more efficient as you read only the directory entry and file that you want to extract.

RandomAccessFiles class The RandomAccessFile class contains the same read(), write() and close() methods as Input and OutputStream Also contains seek() that lets you select a beginning position within the file before reading or writing data Includes capabilities for reading and writing primitive- type values, byte arrays and strings

RandomAccessFile Class NOT compatible with the stream/reader/writer models With a random-access file, you can seek to the desired position and then read and write an amount of bytes Only support seeking relative to the beginning of the file –Not relative to current position of file pointer –However there are methods that report the current position

Methods to support seeking long getFilePointer() Returns the current offset in this file.getFilePointer long length() Returns the length of this file.length void seek(long pos) Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.seek

Constructor Summary RandomAccessFileRandomAccessFile(File file, String mode)FileString Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument. RandomAccessFileRandomAccessFile(String name, String mode) Creates a random access file stream to read from, and optionally to write to, a file with the specified name.String The mode should be either “r” or “rw” –No “w”

Constructor Summary When a RandomAccessFile is created in read-only mode a FileNotFoundException is generated When a RandomAccessFile is created in read-write a zero length file will be created

File Pointer RandomAccessFile supports file pointer which indicates the current location in the file. When the file is first created, the file pointer is set to 0, indicating the beginning of the file. Calls to the read and write methods adjust the file pointer by the number of bytes read or written.

Manipulate file pointer RandomAccessFile contains three methods for explicitly manipulating the file pointer. int skipBytes(int) — Moves the file pointer forward the specified number of bytes void seek(long) — Positions the file pointer just before the specified byte long getFilePointer() — Returns the current byte location of the file pointer

To move the file pointer to a specific byte f.seek(n); To get current position of the file pointer. long n = f.getFilePointer(); To find the number of bytes in a file long filelength = f.length();

Writing Example import java.io.*; public class RandomAccess { public static void main(String args[]) throws IOException { RandomAccessFile myfile = new RandomAccessFile("rand.dat", "rw"); myfile.writeInt(120); myfile.writeDouble(375.50); myfile.writeInt('A'+1); myfile.writeBoolean(true); myfile.writeChar('X');

// set pointer to the beginning of file and read next two items myfile.seek(0); System.out.println (myfile.readInt()); System.out.println (myfile.readDouble()); //set pointer to the 4th item and read it myfile.seek(16); System.out.println

(myfile.readBoolean()); // Go to the end and “ append ” an integer 2003 myfile.seek(myfile.length()); myfile.writeInt(2003); // read 5th and 6th items myfile.seek(17); System.out.printlna Int Double Int boolean Char Int

(myfile.readChar()); System.out.println (myfile.readInt()); System.out.println("File length: "+myfile.length()); myfile.close(); }

Output

Reading Example RandomAccessFile creates random access files –Contains familiar read( ), write( ), open( ), close( ) –seek( ) method selects start position within a file before read or write –Places a file pointer at the selected location –File pointer holds byte number of next file position –Ex: locate 32 nd character in file, which may then be read

Reading Example import java.io.*; public class AccessCharacter { public static void main(String[] args) throws IOException { OutputStream ostream; int c; RandomAccessFile inFile = new RandomAccessFile("AQuote.txt","r"); ostream = System.out; int pos = 32;

try { inFile.seek(pos); c = inFile.read(); System.out.print("The character in position " + pos + " is "); ostream.write(c); }a catch (IOException e) { System.out.println(); inFile.close(); ostream.close(); }

Output

References Object Oriented Software Development using Java- 2 nd edition - Xiaoping Jia Java Programming 3 rd edition – Joyce Farrell