object oriented programming files and streams dr. mike spann [email protected]

37
Object Oriented Programming Files and Streams Files and Streams Dr. Mike Spann Dr. Mike Spann [email protected] [email protected]

Upload: bruce-bradley

Post on 17-Dec-2015

232 views

Category:

Documents


0 download

TRANSCRIPT

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

Object Oriented Programming

Files and StreamsFiles and Streams

Dr. Mike SpannDr. Mike Spann

[email protected]@bham.ac.uk

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

Contents

IntroductionIntroduction Sequential file I/OSequential file I/O Classes Classes FileFile and and DirectoryDirectory SerializationSerialization SummarySummary

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

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

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

Introduction

In C#, streams are simply sequences of bytes No formatting structure is placed on this byte

stream, this is imposed by the application 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

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

Introduction

FileStream object

byte stream

FileStream object

byte stream

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

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

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

Sequential file I/Ousing System;using System.IO; 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]"); } }}

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

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

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

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

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

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);

for (int i = 0; i < 10; i++) { String input = fileReader.ReadLine(); Console.WriteLine(input); } } catch{ Console.WriteLine("Usage: CreateTextFile OutputFile");} }}

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

Sequential file I/O

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

Classes File and Directory

Classes Classes FileFile and and DirectoryDirectory allow an application allow an application to obtain information about files and directories to obtain information about files and directories stored on discstored on disc

Each class contains a large set of static methods Each class contains a large set of static methods for both manipulation and information gatheringfor both manipulation and information gathering These classes could be the basis of a hard disc These classes could be the basis of a hard disc

scanning application to determine usage and scanning application to determine usage and the amount of available storage spacethe amount of available storage space

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

Classes File and Directory

static Method Description

AppendText Returns a StreamWriter that appends text to an existing file or creates a file if one does not exist.

Copy Copies a file to a new file.

Create Creates a file and returns its associated FileStream.

CreateText Creates a text file and returns its associated StreamWriter.

Delete Deletes the specified file.

Exists Returns true if the specified file exists and false otherwise.

GetCreationTime Returns a DateTime object representing when the file was created.

GetLastAccessTime Returns a DateTime object representing when the file was last accessed.

Static methods of File

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

Classes File and Directory

static Method Description

GetLastWriteTime Returns a DateTime object representing when the file was last modified.

Move Moves the specified file to a specified location.

Open Returns a FileStream associated with the specified file and equipped with the specified read/write permissions.

OpenRead Returns a read-only FileStream associated with the specified file.

OpenText Returns a StreamReader associated with the specified file.

OpenWrite Returns a read/write FileStream associated with the specified file.

Static methods of File (cont)

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

Classes File and Directory

static Method Description

CreateDirectory Creates a directory and returns its associated DirectoryInfo object.

Delete Deletes the specified directory.

Exists Returns true if the specified directory exists and false otherwise.

GetDirectories Returns a string array containing the names of the subdirectories in the specified directory.

GetFiles Returns a string array containing the names of the files in the specified directory.

GetCreationTime Returns a DateTime object representing when the directory was created.

GetLastAccessTime Returns a DateTime object representing when the directory was last accessed.

GetLastWriteTime Returns a DateTime object representing when items were last written to the directory.

Move Moves the specified directory to a specified location.

Static methods of Directory

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

Classes File and Directory

As a simple example, we can use an As a simple example, we can use an OpenFileDialogOpenFileDialog box (which only allows files to box (which only allows files to be selected) or a be selected) or a FolderBrowserDialog FolderBrowserDialog (which (which displays the contents of a directory)displays the contents of a directory)

We can then use the We can then use the File File or or DirectoryDirectory classes to classes to print information about the selected itemprint information about the selected item For a file we print the file size and last For a file we print the file size and last

modified datemodified date For a directory, we print its contentsFor a directory, we print its contents

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

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); }}

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

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

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

Demos\Files and Streams\FileTestForm.exe

Classes File and Directory

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

Serialization

It is easy to write the individual fields of a It is easy to write the individual fields of a recordrecord object to a file object to a file For example, we can create a record that stores information For example, we can create a record that stores information

about a studentabout a student NameName AddressAddress ID numberID number Course enrolled forCourse enrolled for etcetc

We can output each field of this record to a file (either text or We can output each field of this record to a file (either text or binary) binary)

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

Serialization

StudentInfo

NameAddressID numberCourse Info

Record file

string string int string

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

Serialization In this example, any program that needs to read the file needs to In this example, any program that needs to read the file needs to

know the format of the dataknow the format of the data 2 strings, an int and then a string2 strings, an int and then a string Also whether each item is on a separate lineAlso whether each item is on a separate line

Object serializationObject serialization allows complete objects to be read or written allows complete objects to be read or written with a single statementwith a single statement

A A serialized objectserialized object is an object represented as a sequence of bytes is an object represented as a sequence of bytes Information is stored about the data types of the objects instance Information is stored about the data types of the objects instance

fields as well as their valuesfields as well as their values Allows the object to be reconstructed (de-serialized) from the Allows the object to be reconstructed (de-serialized) from the

file file

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

Serialization

StudentInfo

NameAddressID numberCourse Info

Record file

StudentInfo object

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

Serialization To serialize an object, the object class needs to be To serialize an object, the object class needs to be

marked with the marked with the [Serializable] [Serializable] attribute or needs to attribute or needs to implement the implement the ISerializableISerializable interface interface

Requires the Requires the System.Runtime.SerializationSystem.Runtime.Serialization namespace namespace Also we require a Also we require a BinaryFormatterBinaryFormatter object to object to

serialize/de-serialize the object before writing to or serialize/de-serialize the object before writing to or reading from filereading from file It’s also possible to serialize objects using SOAP It’s also possible to serialize objects using SOAP

(simple object access protocol) or XML using the (simple object access protocol) or XML using the appropriate formattersappropriate formatters

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

Serialization

Example. A custom serializer GUI Example. A custom serializer GUI

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

Serialization

The user inputs student info. details in the The user inputs student info. details in the corresponding textboxes on the left which corresponding textboxes on the left which through the serialization will be stored in a through the serialization will be stored in a binary filebinary file

The information in the binary file will be The information in the binary file will be deserialized and displayed in the right hand deserialized and displayed in the right hand textboxestextboxes

We will create a simple We will create a simple StudentInfoStudentInfo class and tag class and tag it as it as SerializableSerializable

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

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; }}

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

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 from a binary file back to a textbox }}

Serialization

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

Serializationprivate 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();}

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

Serialization

Demos\Files and Streams\SerializerTestForm.exe

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

Serialization

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

Serialization

Binary serialization is limited as only .NET Binary serialization is limited as only .NET applications can deserialize the data streamapplications can deserialize the data stream

For more general inter-operability especially For more general inter-operability especially across a network, across a network, XML serializationXML serialization is used is used XML is text based and self describing and XML is text based and self describing and

universaluniversal Comprised name/attribute pairsComprised name/attribute pairs XML serialization easy to implement and uses XML serialization easy to implement and uses

text streamstext streams

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

Serialization

We need to insert XML tags into our We need to insert XML tags into our StudentInfo StudentInfo class class Only public properties and fields can be Only public properties and fields can be

serializedserialized[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; }}

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

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; XmlSerializer xmls = new XmlSerializer(typeof(StudentInfo)); 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(); }}

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

Serialization

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

Summary

We have seen how we can use streams to do We have seen how we can use streams to do simple sequential file I/O for binary and simple sequential file I/O for binary and text filestext files

We have looked at how we can use the We have looked at how we can use the FileFile and and DirectoryDirectory classes classes

We have looked at object serialization to We have looked at object serialization to binary and XMLbinary and XML