finally if fin null finclose 26 opening a filestream

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Use BinaryReader/Writer classes for structured binary I/O Use the StreamReader/Writer classes for text I/O Close the file when done You'll normally use try-catch-finally to catch errors Opening a FileStream I Here's the basic structure to open a file for reading FileStream fin = null; try { fin = File.Open(arg[0]); // process the stream here } catch (IOException e) { // deal with file-not-found, etc. } finally { if (fin != null) fin.Close(); } 26 Opening a FileStream II There are two basic ways to open a FileStream Use a static method from the File class fin = File.OpenRead(args[0]); fout = File.OpenWrite(args[1]); Use one of the many FileStream constructors fin = new FileStream(args[0], FileMode.Open, FileAccess.Read); FileAccess and FileMode Two enumerations used with many constructors FileAccess : Read, Write, ReadWrite FileMode : determines how the data is processed Append : only used with Write -- data added to end Create : create and overwrite existing file if it exists CreateNew : create file only if it does not exist Open : file must currently exist OpenOrCreate : opens if it exists, else it is created Truncate : open existing file for writing, truncate contents 27 Serialization We can also take a binary "snapshot" of an object W e can then send the object over a stream Save an obje...
View Full Document

This note was uploaded on 04/04/2014 for the course CS 5950 taught by Professor Staff during the Summer '08 term at Western Michigan.

Ask a homework question - tutors are online