Working with files. RHS – SOC 2 Motivation All our programs so far have only worked with data stored in primary storage (RAM) Data is lost when program.

Slides:



Advertisements
Similar presentations
Lecture 15: I/O and Parsing
Advertisements

The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
Java I/O The Cheat Sheet. Reading and Writing The basic architecture of Java IO is pluggable. The idea is to have some very simple classes do very simple.
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.
CIS 1068 Program Design and Abstraction
Lecture 31 File I/O -Part 2 COMP1681 / SE15 Introduction to Programming.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
1 File Output. 2 So far… So far, all of our output has been to System.out  using print(), println(), or printf() All input has been from System.in 
Chapter 91 Streams and File I/O Chapter 9. 2 Announcements Project 5 due last night Project 6 assigned Exam 2 –Wed., March 21, 7:00 – 8:00 pm, LILY 1105.
Lecture 7 File I/O (and a little bit about exceptions)‏
File-based Persistence: Serializability COMP53 Dec 7, 2007.
Files and Streams. Goals To be able to read and write text files To be able to read and write text files To become familiar with the concepts of text.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 12 File Input and Output.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Chapter 20 – Streams and Binary Input/Output Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
Two Ways to Store Data in a File Text format Binary format.
Chapter 16 Streams. Chapter Goals To be able to read and write text files To become familiar with the concepts of text and binary formats To learn about.
Files and Streams 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
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.
CIS 270—Application Development II Chapter 14—Files and Streams.
Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) –it acts as.
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.
Working with files By the end of this lecture you should be able to: explain the principles of input and output and identify a number of different input.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
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.
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.
Fall 2006Adapted from Java Concepts Companion Slides1 Files and Streams Advanced Programming ICOM 4015 Lecture 16 Reading: Java Concepts Chapter 16.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Two Ways to Store Data in a File  Text format  Binary format.
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.
CIS 270—App Dev II Big Java Chapter 19 Files and Streams.
CSE 501N Fall ‘09 18: Files and Streams 06 November 2009 Nick Leidenfrost.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
1 Software 1 Java I/O. 2 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating.
 Pearson Education, Inc. All rights reserved Files and Streams.
Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from.
Streams & Files. Java I/O Classes Saving data to / Loading data from files Two Choices: Binary-Formatted or Text-Formatted Data – int x = 1234; – Binary.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
Files and Serialization. Files Used to transfer data to and from secondary storage.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
Streams. RHS – SWC 2 Binary files A binary file contains ”raw” bytes that can be interpreted as almost anything Can have any extension Can be created.
Lecture 8: I/O Streams types of I/O streams Chaining Streams
Java Text I/O CS140 Dick Steflik. Reader Abstract super class for character based input Subclasses: – BufferedReader – CharArrayReader – FilterReader.
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
File - CIS 1068 Program Design and Abstraction
File Input / Output.
University of Central Florida COP 3330 Object Oriented Programming
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
Chapter 13: File Input and Output
Working with files.
Working with files.
Chapter 17 Binary I/O Dr. Clincy - Lecture.
Streams and File I/O Chapter 14.
CSS 161: Fundamentals of Computing
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
Web Design & Development Lecture 8
CS 240 – Advanced Programming Concepts
David Davenport Spring 2005
Presentation transcript:

Working with files

RHS – SOC 2 Motivation All our programs so far have only worked with data stored in primary storage (RAM) Data is lost when program is terminated Almost all ”real” programs allow us to save the state – by some definition – of the program to permanent storage (e.g disk) Such permanent storage is often a file

RHS – SOC 3 What is a file? A collection of bytes, stored on a perma- nent storage media Bytes can be interpreted as text, numerics, picture, etc. Files have a name, and a position (path) –Myschedule.doc (name) –C:\documents\per\rhs (path)

RHS – SOC 4 Text files A text file just contains characters (bytes inter- preted as characters) Usually named.txt Created with simple text editor like Notepad, or NetBeans…

RHS – SOC 5 Text files and Java It is rather easy to read a text file in Java – we use the FileReader class and the Scanner class FileReader reader = new FileReader(”input.txt”); Scanner in = new Scanner(reader); String line = in.nextLine();

RHS – SOC 6 Text files and Java FileReader reader = new FileReader(”input.txt”); Scanner in = new Scanner(reader); String line = in.nextLine(); Constructor takes file name as a String (remember ””) FileReader itself cannot be used for reading – need a Scanner object Several next… methods available next() nextInt() nextDouble() …

RHS – SOC 7 Text files and Java FileReader reader = new FileReader(”input.txt”); Scanner in = new Scanner(reader); int lineCount = 0; while (in.hasNextLine()) { String line = in.nextLine(); lineCount++; } in.close(); System.out.println(”Lines in file: ” + lineCount);

RHS – SOC 8 Text files and Java When providing a file path as a constant string, the string mus look like this: ”c:\\documents\\psl\\work.txt”; Notice the use of double backslash! Recall that \ is used for escape characters! We do not need double backslash when e.g the user types the path in a dialog

RHS – SOC 9 Text files and Java It is also easy to write to a file in Java – we use the PrintWriter class PrintWriter out = new PrintWriter(”output.txt”); That’s it – we can now use the well- known print(…) and println(…) methods

RHS – SOC 10 Text files and Java PrintWriter out = new PrintWriter(”output.txt”); for (int i = 0; i < 10; i++) { out.println(”Writing to a file is easy!”); } out.close(); System.out.println(”Done writing to file”);

RHS – SOC 11 Text files and Exceptions Working with files is easy, but… …errors beyond the control of the pro- grammer can happen! –File was not found –File was not a text file –File was different format than expected –…and so on

RHS – SOC 12 Text files and Exceptions Code for handling files should include proper handling of exceptions! IOException class, and subclass thereof We can define more specific classes as well

RHS – SOC 13 Exercises Self-check: -- Review: R11.1, R11.2 Programming: P11.1, P11.7

RHS – SOC 14 Binary files A binary file contains ”raw” bytes that can be interpreted as almost anything Can have any extension Can be created from various sources

RHS – SOC 15 Binary files Note that a binary file does usually not contain information about itself (metadata) We must know the meaning of the file in advance –Picture –Object data –Encrypted data

RHS – SOC 16 Binary files and Java In Java, a binary file is considered a ”stream” of bytes We generally use InputStream and OutputStream to handle binary data For binary files, we use: –Read: FileInputStream –Write: FileOutputStream

RHS – SOC 17 Binary files and Java FileInputStream inS = new FileInputStream(”input.dat”); boolean done = false; while (!done) { int next = inS.read(); byte nextByte; if (next != -1) { nextByte = (byte)next;... // Do something with nextByte } else {done = true; } } inS.close();

RHS – SOC 18 Binary files and Java FileOutputStream outS = new FileOutputStream(”output.dat”); byte nextByte; boolean done = false; while (!done) {... // We get bytes to write from somewhere outS.write(nextByte); } outS.close();

RHS – SOC 19 Binary files – random access Sequential processing of binary files is fairly simple – but possibly inefficient What if a binary file contained data for thousands of bank accounts, and we just needed data for one…? Java also allows ”random access” to data in a binary file

RHS – SOC 20 Binary files – random access A file also has a file pointer The file pointer indicates where to read/write the next time

RHS – SOC 21 Binary files – random access Random access in a file is done using the RandomFileAccess class –new RandomAccessFile(”data.bin”,”rw”) –f.seek(pointerPos) –int pointerPos = f.getFilePointer() –long fileLen = f.length();

RHS – SOC 22 Binary files – random access Random access can be efficient when dealing with large binary files Again, no help from Java – you must decide and obey a data format yourself If you overwrite data – too bad… A little bit of help – Java does offer methods for read/write of numeric types from a binary file

RHS – SOC 23 Binary files and Java Java only provides simple methods for reading/writing binary files – what else could it do…? We are responsible for interpreting and processing the stream of bytes Java gets the bytes for us, it does not try to analyse them…

RHS – SOC 24 Object streams Wouldn’t it be nice, if we could –Convert an object to binary format –Write the binary data to a file –Close the program –Open the program anew –Read the binary data from the file –Convert the data back to an object

RHS – SOC 25 Object streams An object stream can do just that! Two classes available –ObjectOutputStream –ObjectInputStream Only prerequisite; a class must implement the Serializable interface, in order to be writable and readable by an object stream

RHS – SOC 26 Object streams public interface Serializable { // Empty... }

RHS – SOC 27 Object streams Typical way to use object streams: –Define a class where one object can contain all relevant data (for instance a Bank class) –Let the class implement Serializable –Use the class for writing/reading data This is extremely useful for saving in- memory data to a file

RHS – SOC 28 Object streams public class Bank implements Serializable {...} // Writing Bank data to a file Bank myBank = new Bank();... // Enter data into myBank object FileOutputStream fos = new FileOutputStream(”bankA.dat”); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(myBank); // Reading Bank data from a file FileInputStream fis = new FileInputStream(”bankB.dat”); ObjectInputStream ois = new ObjectInputStream(fis); myBank = (Bank)ois.readObject();

RHS – SOC 29 Exercises Self-check: 1, 6, 7, 8 Review: R19.3, R19.5, R19.7 Programming: –The Car Rental Project