Document 7741940

Download Report

Transcript Document 7741940

Input and Output
Objectives
• Survey IO facilities in .NET Framework Class Library
– file and directory management
– text files
– binary files
– object serialization
2
IO Library
• Input/output library in System.IO namespace
• Support provided for:
– file and directory management
– text files
– binary files
– simple type conversion to/from binary
3
Files and directories
• Two primary classes to work with files and directories
– perform file system interaction
– generally do not manipulate file contents
– derived from common base
FileSystemInfo
DirectoryInfo
FileInfo
4
FileSystemInfo
• Files and directories have some operations in common
– provided in base class FileSystemInfo
name
public abstract class FileSystemInfo
{
public abstract string Name
{
public string
FullName {
public string
Extension {
public
public
public
public
public
characteristics
abstract bool
DateTime
DateTime
DateTime
FileAttributes
...
get; }
get; }
get; }
Exists
CreationTime
LastAccessTime
LastWriteTime
Attributes
{
{
{
{
{
get;
get;
get;
get;
get;
}
set;
set;
set;
set;
}
}
}
}
public void Delete() ...
...
delete
}
5
DirectoryInfo
• DirectoryInfo represents a directory
– methods provided to examine and manipulate
– inherits common operations from FileSystemInfo
constructor
public sealed class DirectoryInfo : FileSystemInfo
{
public DirectoryInfo(string path) ...
public DirectoryInfo Parent { get; }
public DirectoryInfo Root
{ get; }
navigation
public
public
public
public
manipulation
void
void
void
DirectoryInfo
Create
()
...
MoveTo
(string destDirName) ...
Delete
(bool
recursive ) ...
CreateSubdirectory(string path
) ...
public FileInfo
[] GetFiles
() ...
public DirectoryInfo [] GetDirectories
() ...
public FileSystemInfo[] GetFileSystemInfos() ...
...
contents
}
6
FileInfo
• FileInfo represents a file
– methods provided to examine and manipulate
– inherits common operations from FileSystemInfo
constructor
public sealed class FileInfo : FileSystemInfo
{
public FileInfo(string fileName) ...
public long Length { get; }
length
public string
DirectoryName { get; }
public DirectoryInfo Directory
{ get; }
location
public FileInfo CopyTo(string destFileName) ...
public FileInfo CopyTo(string destFileName, bool overwrite) ...
public void
MoveTo(string destFileName) ...
...
manipulation
}
7
Application: List contents
• Can examine contents of a directory
void List(string path)
{
DirectoryInfo directory = new DirectoryInfo(path);
FileInfo
[] files
= directory.GetFiles
();
DirectoryInfo[] directories = directory.GetDirectories();
contents
foreach (FileInfo f in files)
Console.WriteLine(f.Name);
files
foreach (DirectoryInfo d in directories)
Console.WriteLine(d.Name);
directories
}
8
Application: Find file
• Can search file system to find specified files
search with
pattern
recursive call
for each
subdirectory
void Find(string filename, DirectoryInfo root, ArrayList results)
{
foreach (FileInfo f in root.GetFiles(filename))
results.Add(f.FullName);
foreach (DirectoryInfo d in root.GetDirectories())
Find(filename, d, results);
}
DirectoryInfo root
ArrayList
results
= new DirectoryInfo(@"C:\WINDOWS");
= new ArrayList();
Find("mscoree.dll", root, results);
foreach (string s in results)
Console.WriteLine(s);
9
Utility classes
• Three utility classes also work with files and directories
– Path
– Directory
– File
10
Path
• Path provides static methods to manipulate a path string
– most do not interact with the file system
public sealed class Path
{
public static bool
HasExtension
(string path) ...
public static string GetExtension
(string path) ...
public static string ChangeExtension(string path, string extension) ...
public static string GetDirectoryName(string path) ...
public static string GetFileName
(string path) ...
public static string GetFileNameWithoutExtension(string path) ...
public static readonly char DirectorySeparatorChar;
public static readonly char VolumeSeparatorChar;
public static readonly char PathSeparator;
...
}
11
Application: parse path
• Path methods useful to parse path into constituent parts
C:\WINDOWS\system32
public void Parse(string path)
{
string a = Path.GetDirectoryName
mscoree.dll
string b = Path.GetFileName
mscoree
(path);
(path);
string c = Path.GetFileNameWithoutExtension(path);
.dll
C:\
string d = Path.GetExtension
(path);
string e = Path.GetPathRoot
(path);
...
}
string path = @"C:\WINDOWS\system32\mscoree.dll";
Parse(path);
12
Directory
• Directory has static methods to manipulate directories
– most have analogues in DirectoryInfo
– several offer unique functionality
all drives on system
public sealed class Directory
{
public static string[] GetLogicalDrives()
current directory
similar methods in
DirectoryInfo
public static string
public static void
GetCurrentDirectory()
SetCurrentDirectory(string path)
public
public
public
public
public
...
Exists
(string path) ...
GetFiles
(string path) ...
GetDirectories(string path) ...
Delete
(string path)
Move(string source, string dest)
static
static
static
static
static
bool
string[]
string[]
void
void
}
13
Application: examine drives
• Can examine all logical drives
– use Directory.GetLogicalDrives to get drives
– use Directory.Exists to determine if disk in drive
all drives
disk in drive?
string[] drives = Directory.GetLogicalDrives();
foreach (string s in drives)
{
if (Directory.Exists(s))
...
}
14
File
• File has static methods to manipulate files
– all have analogues in FileInfo
similar methods
in FileInfo
public sealed class File
{
public static bool Exists(string
public static void Delete(string
public static void Copy (string
public static void Move (string
...
}
path) ...
path) ...
source, string dest) ...
source, string dest) ...
15
Choice of file / directory class
• Must sometimes decide which class to use
– File vs. FileInfo
– Directory vs. DirectoryInfo
• Static methods
– can offer more convenient usage syntax
– require permission check on each call
• Instance methods
– must instantiate object
– some permission checks can be done once in constructor
16
File contents manipulation
• Classes provided to manipulate file contents
– separate classes for text and binary files
– filters convert simple types to/from bytes for binary storage
– support for disk or memory files
17
Character IO
• Classes provided to do character IO
– most methods defined in base classes
– derived classes specialized for data location and operation
TextWriter
StreamWriter
write to disk
StringWriter
write to StringBuilder
TextReader
StreamReader
read from disk
StringReader
read from string
18
StreamWriter
• StreamWriter writes characters to text file
– open file with one of many constructors
– write with overloaded Write / WriteLine methods
– close
char, bool, string,
short, int, long,
float, double, etc.
automatically
converted to string
using ToString
text file
open
StreamWriter sw = new StreamWriter("Chores.txt");
int n = 3;
write
sw.WriteLine("Go to pet store");
sw.Write("Feed all ");
sw.Write(n);
sw.WriteLine(" cats");
close
sw.Close();
19
StreamReader
• StreamReader reads characters from text file
– open file with one of many constructors
– read characters or strings with Read / ReadLine methods
– close
char, string
can read only
char or string
text file
open
StreamReader sr = new StreamReader("Chores.txt");
string s;
read
while ((s = sr.ReadLine()) != null)
Console.WriteLine(s);
close
sr.Close();
20
Byte IO
• Classes provided to do byte IO
– most methods defined in base class
• Two possible data locations provided in System.IO
– disk
– memory
Stream
FileStream
read/write disk
MemoryStream
read/write byte array
21
Stream methods
• Stream offers extensive functionality
– read / write bytes
– random access
– asynchronous read / write
read/write
public abstract class Stream ...
{
public virtual int ReadByte () ...
public virtual void WriteByte(byte value) ...
public abstract int Read (byte[] buffer, int offset, int count);
public abstract void Write(byte[] buffer, int offset, int count);
random
access
public abstract long Seek
(long offset, SeekOrigin origin);
public abstract long Position { get; set; }
asynch
public
public
public
public
...
virtual
virtual
virtual
virtual
IAsyncResult
int
IAsyncResult
void
BeginRead (...)
EndRead
(...)
BeginWrite(...)
EndWrite (...)
...
...
...
...
}
22
FileStream
• FileStream supports read / write bytes to disk file
open
write
back up 2 bytes
back up to beginning
close
FileStream f = new FileStream
(
"Bytes.dat",
FileMode.Create,
FileAccess.ReadWrite
);
f.WriteByte((byte)10);
f.WriteByte((byte)20);
f.WriteByte((byte)30);
f.WriteByte((byte)90);
f.WriteByte((byte)50);
byte,
byte[]
binary file
f.Seek(-2, SeekOrigin.Current);
f.WriteByte((byte)40);
f.Seek(0, SeekOrigin.Begin);
int b = f.ReadByte();
f.Close();
23
Simple type output
• BinaryWriter converts many core types to binary
– must be used with a stream for storage
– Write methods convert and write bytes to backing stream
char, bool, string,
short, int, long,
float, double, etc.
simple types
converter
bytes
binary file
data store
FileStream data = new FileStream("Bytes.dat", FileMode.Create);
converter
BinaryWriter converter = new BinaryWriter(data);
write
close both
streams
converter.Write(17);
converter.Write(3.14);
converter.Write("hello");
converter.Close();
24
Simple type input
• BinaryReader reconstructs types from binary
– must be given a stream containing bytes
– Read methods read from backing stream and convert
char, bool, string,
short, int, long,
float, double, etc.
simple types
converter
bytes
binary file
data store
FileStream data = new FileStream("Bytes.dat", FileMode.Open);
converter
BinaryReader converter = new BinaryReader(data);
read
close both
streams
int
i = converter.ReadInt32 ();
double d = converter.ReadDouble();
string s = converter.ReadString();
converter.Close();
25
Serialization
• Can save/restore state of object to stream
– called serialization
x 1
y 2
save
serialize
Point x=1, y=2 ...
restore
Point x=1, y=2 ...
deserialize
x 1
y 2
26
Serializable attribute
• Type author must explicitly allow serialization
– tag with Serializable attribute to allow
– otherwise get SerializationException
allow points to
be serialized
[Serializable]
class Point
{
int x;
int y;
...
}
27
Formatter
• BinaryFormatter used to serialize/deserialize object
– in namespace
System.Runtime.Serialization.Formatters.Binary
save object
to stream
public sealed class BinaryFormatter ...
{
public void Serialize(Stream destination, object o)
{
...
}
restore object
from stream
public object Deserialize(Stream source)
{
...
}
...
}
28
Save
• Use Serialize method to save object to stream
void Write()
{
FileStream dest = new FileStream("MyData.dat", FileMode.Create);
Point data = new Point(1, 2);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(dest, data);
...
}
29
Restore
• Use Deserialize method to restore object from stream
– return type is object, typical to downcast
void Read()
{
FileStream source = new FileStream("MyData.dat", FileMode.Open);
BinaryFormatter formatter = new BinaryFormatter();
Point data = (Point)formatter.Deserialize(source);
...
}
30
Object graph
• Serialization preserves object graph
– all referenced objects are serialized
– graph rebuilt when deserialized
c
center
radius 3
x 1
y 2
Both circle and center
point would be serialized
31
Summary
• IO facilities provided by .NET Framework class library
– in System.IO namespace
• Can manipulate files and directories
• Can read/write file contents
– characters
– bytes
• Can convert simple types to/from binary format
• Serialization allows objects to be read/written to stream
32