Working with files.

Slides:



Advertisements
Similar presentations
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Advertisements

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.
©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)‏
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.
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.
©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.
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.
MIS316 – BUSINESS APPLICATION DEVELOPMENT – Chapter 14 – Files and Streams 1Microsoft Visual C# 2012, Fifth Edition.
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.
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.
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.
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.
Fall 2006Adapted from Java Concepts Companion Slides1 Files and Streams Advanced Programming ICOM 4015 Lecture 16 Reading: Java Concepts Chapter 16.
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.
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.
1 CSE 331 Memento Pattern and Serialization slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
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
Programming in Java Files and I/O Streams
Working with files.
Streams and File I/O Chapter 14.
CSS 161: Fundamentals of Computing
MSIS 670: Object-Oriented Software Engineering
Chapter 16 Streams.
Workshop for Programming And Systems Management Teachers
CSE 331 Memento Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
Workshop for Programming And Systems Management Teachers
Web Design & Development Lecture 8
CS 240 – Advanced Programming Concepts
David Davenport Spring 2005
Presentation transcript:

Working with files

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 DCS – SWC

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) DCS – SWC

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… DCS – SWC

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(); DCS – SWC

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

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); DCS – SWC

Text files and Java When providing a file path as a constant string, the string must 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 DCS – SWC

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 DCS – SWC

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”); DCS – SWC

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 DCS – SWC

Text files and Exceptions Code for handling files should include proper handling of exceptions! IOException class, and subclasses thereof We can define more specific classes as well DCS – SWC

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 DCS – SWC

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 DCS – SWC

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 DCS – SWC

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(); DCS – SWC

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(); DCS – SWC

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 DCS – SWC

Binary files – random access A file also has a file pointer The file pointer indicates where to read/write the next time 1 9 7 7 5 1 2 9 DCS – SWC

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(); DCS – SWC

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 DCS – SWC

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… DCS – SWC

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 DCS – SWC

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 DCS – SWC

Object streams public interface Serializable { // Empty... } DCS – SWC

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 DCS – SWC

Object streams This is very convenient, but BE AWARE of a common ”trap” in serialization! To serialize an object, all fields in the object must themselves be serializable! DCS – SWC

Object streams Example: We want to make ItemCatalog serializable An ItemCatalog class contains an… ArrayList<Item> instance field, which contains several… Item objects We want to make ItemCatalog serializable DCS – SWC

Object streams We must then mark the ItemCatalog class as being serializable ArrayList is itself serializable, so all is good… …BUT we must also mark the Item class itself as being serializable! Otherwise, an IOException will be thrown DCS – SWC

Object streams public class Bank implements Serializable {...} Bank myBank = new Bank(); // Enter data into myBank object FileOutputStream fos = new FileOutputStream(”bank.dat”); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(myBank); oos.close(); fos.close(); DCS – SWC

Object streams public class Bank implements Serializable {...} Bank myBank = new Bank(); // Reading Bank data from a file FileInputStream fis = new FileInputStream(”bank.dat”); ObjectInputStream ois = new ObjectInputStream(fis); myBank = (Bank)ois.readObject(); ois.close(); fis.close(); DCS – SWC