Object Oriented Programming

Slides:



Advertisements
Similar presentations
Reading and Writing Text Files Svetlin Nakov Telerik Corporation
Advertisements

Pemrograman VisualMinggu …12… Page 1 MINGGU Ke Duabelas Pemrograman Visual Pokok Bahasan: File and Stream Tujuan Instruksional Khusus: Mahasiswa dapat.
Object Oriented Programming Files and Streams Dr. Mike Spann
C# - Files and Streams Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access.
Files & Streams. Files Introduction Files are used for long-term retention of large amounts of data, even after the program that created the data terminates.
Serialization objects created in a program reside in RAM through references object o; heap stack content.
Object-Oriented Application Development Using VB.NET 1 Chapter 13 Introduction to Data Access Classes and Persistence.
ASP.NET Programming with C# and SQL Server First Edition
Creating Sequential-Access File  Serializable attribute indicates to the compiler that objects of a class can be serialized– written to or read from a.
Sequential-access file Create, read and write an object into a sequential-access file Serialize and deserialize the object to write and read from a data.
C# Programming: From Problem Analysis to Program Design1 Working with Files C# Programming: From Problem Analysis to Program Design 3 rd Edition 13.
MIS316 – BUSINESS APPLICATION DEVELOPMENT – Chapter 14 – Files and Streams 1Microsoft Visual C# 2012, Fifth Edition.
Windows Programming Using C# Windows Services, Serialization, and Isolated Storage.
Computer and Programming File I/O File Input/Output Author: Chaiporn Jaikaeo, Jittat Fakcharoenphol Edited by Supaporn Erjongmanee Lecture 13.
Lecture Set 12 Sequential Files and Structures Part B – Reading and Writing Sequential Files.
Object Oriented Programming Classes and Objects Dr. Mike Spann
1 Binary Files ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT
Visual C Sharp – File I/O - 1 Variables and arrays only temporary - lost when a program terminates Files used for long term storage (Data bases considered.
Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda.
Object Oriented Programming Graphical User Interfaces Dr. Mike Spann
C# B 1 CSC 298 Writing a C# application. C# B 2 A first C# application // Display Hello, world on the screen public class HelloWorld { public static void.
Serialization  What is Serialization?  System.Serialization  Scenarios in Serialization  Basic Serialization  Custom Serialization.
File I/O 11_file_processing.ppt
 2006 Pearson Education, Inc. All rights reserved Files and Streams.
1 14/10/58Dr.Mud-Armeen Munlin 1 Files and Streams ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT
File I/O Static void Main( ) {... } data. Topics I/O Streams Reading and Writing Text Files Formatting Text Files Handling Stream Errors File Pointers.
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
Serialization What is Serialization Serialization is the process of converting an object, or a connected graph of objects, stored within computer memory,
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.
Lecture 19 Serialization Richard Gesick. Serialization Sometimes it is easier to read or write entire objects than to read and write individual fields.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
CS360 Windows Programming
Copyright © 2012 Pearson Education, Inc. Chapter 5 Loops, File, and Random Numbers.
BIM313 – Advanced Programming File Operations 1. Contents Structure of a File Reading/Writing Texts from/to Files File and Directory Operations 2.
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.
CSCI 3328 Object Oriented Programming in C# Chapter 11: Files and Streams -- Exercises 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg,
Input and Output 23: Input and Output
CSC 298 Streams and files.
Chapter 21 – Files and Streams 1 Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access.
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 11 Data Files.
CSCI 3328 Object Oriented Programming in C# Chapter 11: Files and Streams 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539
Files and Streams. What is a file? Up until now, any stored data within a program is lost when the program closes. A file is a permanent way to store.
Object-Oriented Application Development Using VB.NET 1 Chapter 13 Introduction to Data Access Classes and Persistence.
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.
Files and Streams Lec Introduction  Files are used for long-term retention of large amounts of data, even after the program that created the.
INF230 Basics in C# Programming
Input and Output 23: Input and Output
C# Programming: From Problem Analysis to Program Design
IS444: Modern tools for applications development
18 Files and Streams.
Serialization.
CHAPTER 5 JAVA FILE INPUT/OUTPUT
IS444: Modern tools for applications development
I/O Basics.
Lectures 12 Files & Streams Dr. Eng. Ibrahim El-Nahry.
CSCI 3327 Visual Basic Chapter 11: Files and Streams
Files and Streams.
Files and Streams Lect3 CT1411.
Sequential Input and Output using Text Files
File Input/Output (I/O)
Files & Streams.
The University of Texas – Pan American
CSCI 3328 Object Oriented Programming in C# Chapter 11: Files and Streams -- Exercises UTPA – Fall 2012 This set of slides is revised from lecture slides.
Files and Streams Lect10 GC201 12/1/2015.
Fundaments of Game Design
BO65: PROGRAMMING WRITING TO TEXT FILES.
CSCI 3328 Object Oriented Programming in C# Chapter 11: Files and Streams UTPA – Fall 2012 This set of slides is revised from lecture slides of Prof.
Files and Streams.
Chapter 11 Saving Data and Objects In Files
Presentation transcript:

Object Oriented Programming Files and Streams Dr. Mike Spann m.spann@bham.ac.uk

Contents Introduction Sequential file I/O Classes File and Directory Serialization Summary

Introduction Most applications require data to be stored in files Spreadsheets Word processing etc C# has an extensive set of classes for handling files of various types These are to be found in the System.IO namespace Associated with files is the general concept of streams which can be applied to both files and networks

Introduction In C#, streams are simply sequences of bytes No formattng structure is placed on this byte stream, this is imposed by the appliction We can read a byte stream from an input stream object We can write a byte stream to an output stream object The input and output stream objects are created from class FileStream

Introduction FileStream object byte stream FileStream object

Sequential file I/O There are many classes in the FCL for file handling FileStream is the basic file for handling I/O from binary files The constructor opens a stream object and specifies the filename and file access (read, write etc) It provides a Read() and Write() method Its normal to enclose file handling code in a try{} catch{} clause to catch any exceptions thrown

Sequential file I/O using System; using System.IO; class FileCopy {   class FileCopy { public static void Main(String[] args){ try{ FileStream fromStream = new FileStream(args[0], FileMode.Open, FileAccess.Read); FileStream toStream = new FileStream(args[1], FileMode.Create, FileAccess.Write); Byte[] buffer = new Byte[fromStream.Length]; fromStream.Read(buffer, 0, buffer.Length); toStream.Write(buffer, 0, buffer.Length); }catch{ Console.WriteLine("Usage: FileCopy [FromFile] [ToFile]"); }

Sequential file I/O FileStream.Read() and FileStream.Write() are for binary files Data is stored in files as bytes which is efficient but not humanly readable A text file consists of information stored in humanly readable form For example the number 150 would be stored as ‘1’ ‘5’ ‘0’ instead of the binary representation of 150 (10010110) C# has a number of classes (descended from the abstract TextReader and TextWriter classes) for handling text i/o

Sequential file I/O For text files, classes StreamReader and StreamWriter are provided These are derived from TextReader and TextWriter They use the familiar ReadLine() and WriteLine() methods for doing formatted I/O Note that the Console class has StreamReader and StreamWriter objects and uses their ReadLine() and WriteLine() methods for doing console-based I/O

using System; using System.IO; class CreateTextFile { public static void Main(String[] args) try FileStream toStream = new FileStream(args[0], FileMode.Create, FileAccess.Write); StreamWriter fileWriter = new StreamWriter(toStream); for (int i = 0; i < 10; i++) fileWriter.WriteLine("i= " + i); fileWriter.Close(); toStream.Close(); FileStream fromStream = new FileStream(args[0], FileMode.Open, FileAccess.Read); StreamReader fileReader = new StreamReader(fromStream); String input = fileReader.ReadLine(); Console.WriteLine(input); } catch{Console.WriteLine("Usage: CreateTextFile OutputFile");

Sequential file I/O

Classes File and Directory Classes File and Directory allow an application to obtain information about files and directories stored on disc Each class contains a large set of static methods for both manipulation and information gathering These classes could be the basis of a hard disc scanning application to determine usage and the amount of available storage space

Classes File and Directory

Classes File and Directory

Classes File and Directory

Classes File and Directory As a simple example, we can use an OpenFileDialog box (which only allows files to be selected) or a FolderBrowserDialog We can then use the File or Directory classes to print information about the selected item For a file we print the file size and last modified date For a directory, we print its contents

using System; using System.Windows.Forms; using System.IO; public partial class FileTestForm1 : Form { public FileTestForm1() { InitializeComponent(); } private void openFileDialog1_FileOk(object sender, CancelEventArgs e) string fileName = openFileDialog1.FileName; if (File.Exists(fileName)) displayFileInfo(fileName); } private void displayFileInfo(string fileName) { // Displays file information } private void displayDirectoryInfo(string pathName) { // Displays directory information } private void button1_Click(object sender, EventArgs e) { openFileDialog1.ShowDialog(); } private void button2_Click(object sender, EventArgs e) folderBrowserDialog1.ShowDialog(); string pathName = folderBrowserDialog1.SelectedPath; if (Directory.Exists(pathName)) displayDirectoryInfo(pathName);

Classes File and Directory private void displayFileInfo(string fileName) { outputTextBox.Text += "\r\n\r\nFile: " + fileName + ":\r\n"; DateTime creationTime = File.GetCreationTime(fileName); outputTextBox.Text += "Created: " + creationTime.ToString() + "\r\n"; DateTime lastModifiedTime = File.GetLastAccessTime(fileName); outputTextBox.Text += "Last accessed: " + lastModifiedTime.ToString() + "\r\n"; } private void displayDirectoryInfo(string pathName) string[] directoryList; directoryList = Directory.GetDirectories(pathName); outputTextBox.Text += "\r\n\r\nDirectory Contents:\r\n"; // Output directory contents for (int i = 0; i < directoryList.Length; i++) outputTextBox.Text += directoryList[i] + "\r\n";

Classes File and Directory Demos\Files and Streams\FileTestForm.exe

Serialization It is easy to write the individual fields of a record object to a file For example, we can create a record that stores information about a student Name Address ID number Course enrolled for etc We can output each field of this record to a file (either text or binary)

Serialization Record file StudentInfo Name Address ID number string string int string StudentInfo Name Address ID number Course Info

Serialization In this example, any program that needs to read the file needs to know the format of the data 2 strings, an int and then a string Also whether each item is on a separate line Object serialization allows complete objects to be read or written with a single statement A serialized object is an object represented as a sequence of bytes Information is stored about the data types of the objects instance fields as well as their values Allows the object to be reconstructed (de-serialized) from the file

Serialization Record file StudentInfo Name Address ID number StudentInfo object StudentInfo Name Address ID number Course Info

Serialization To serialize an object, the object class needs to be marked with the [Serializable] attribute or needs to implement the ISerializable interface Requires the System.Runtime.Serialization namespace Also we require a BinaryFormatter object to serialize/de-serialize the object before writing to or reading from file It’s also possible to serialize objects using SOAP (simple object access protocol) or xml using the appropriate formatters

Serialization Example. A custom serializer GUI

Serialization The user inputs student info. details in the corresponding textboxes on the left which through the serialization will be stored in a binary file The information in the binary file will be deserialized and displayed in the right hand textboxes We will create a simple StudentInfo class and tag it as Serializable

Serialization [Serializable] class StudentInfo { public string Name, Address, CourseInfo; public int ID; public StudentInfo() {} public StudentInfo(String n, String a, String ci, int id) Name = n; Address = a; CourseInfo = ci; ID = id; }

Serialization using System.Windows.Forms; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; public partial class SerializerTestForm1 : Form { private String fileName = Directory.GetCurrentDirectory() + "\\output1.txt"; public SerializerTestForm1() InitializeComponent(); } private void button1_Click(object sender, EventArgs e) //Serialize textbox data to a binary file private void button2_Click(object sender, EventArgs e) //De-Serialize a binary data back to textbox data

Serialization private void button1_Click(object sender, EventArgs e) { button1.Enabled = false; String name = textBox1.Text; String address = textBox2.Text; int id = Convert.ToInt32(textBox3.Text); String courseInfo = textBox4.Text; StudentInfo s = new StudentInfo(name,address,courseInfo,id); FileStream filestream = new FileStream(fileName, FileMode.Create); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(filestream, s); filestream.Close(); button1.Enabled = true; } private void button2_Click(object sender, EventArgs e) FileStream filestream2 = new FileStream(fileName,FileMode.Open); BinaryFormatter bf2 = new BinaryFormatter(); StudentInfo si= new StudentInfo(); si = (StudentInfo)bf2.Deserialize(filestream2); textBox8.Text = si.Name; textBox7.Text = si.Address; textBox6.Text = ""+si.ID; textBox5.Text = si.CourseInfo; filestream2.Close();

Serialization Demos\Files and Streams\SerializerTestForm.exe

Serialization

Serialization Binary serialization is limited as only .NET applications can deserialize the data stream For more general inter-operability especially across a network, xml serialization is used xml is text based and self descibing and universal Comprised name/attribute pairs xml serialization easy to implement and uses text streams

Serialization We need to insert xml tags into our StudentInfo class Only public properties and fields can be serialized [XmlRoot("studentInfo")] public class StudentInfo { [XmlAttribute("name")] public string Name; [XmlAttribute("address")] public string Address; [XmlAttribute("course")] public string CourseInfo; [XmlAttribute("id")] public int ID; public StudentInfo() { } public StudentInfo(String n, String a, String ci, int id) Name = n; Address = a; CourseInfo = ci; ID = id; }

using System; using System.Windows.Forms; using System.IO; using System.Xml; using System.Xml.Serialization; public partial class xmlSerializerTestForm1 : Form { private String fileName = Directory.GetCurrentDirectory() + "\\output1.xml"; public xmlSerializerTestForm1() {InitializeComponent();} private void button1_Click(object sender, EventArgs e) button1.Enabled = false; String name = textBox1.Text; String address = textBox2.Text; int id = Convert.ToInt32(textBox3.Text); String courseInfo = textBox4.Text; StudentInfo si = new StudentInfo(name, address, courseInfo, id); XmlSerializer xmls = new XmlSerializer(typeof(StudentInfo)); TextWriter w = new StreamWriter(fileName); xmls.Serialize(w, si); w.Close(); button1.Enabled = true; } private void button2_Click(object sender, EventArgs e) StudentInfo si; TextReader r = new StreamReader(fileName); si = (StudentInfo)xmls.Deserialize(r); textBox8.Text = si.Name; textBox7.Text = si.Address; textBox6.Text = "" + si.ID; textBox5.Text = si.CourseInfo; r.Close();

Serialization

Summary We have seen how we can use streams to do simple sequential file I/O for binary and text files We have looked at how we can use the File and Directory classes We have looked at object serialization to binary and xml