140 likes | 263 Views
Prototyping for HCI. Spring 2004 (Week 9) Jorge A. Toro. The Language. File I/O. File I/O. Here, we will deal with text files only. In VB.NET, different classes handle different aspects of text files. One class deals with reading files One class deals with writing into files Etc….
E N D
Prototyping for HCI Spring 2004 (Week 9) Jorge A. Toro
The Language File I/O
File I/O • Here, we will deal with text files only. • In VB.NET, different classes handle different aspects of text files. • One class deals with reading files • One class deals with writing into files • Etc…
File I/O • IO.StreamReader class • Objects of this class are capable of reading text files • IO.StreamWriter class • Objects of this class are capable of writing into text files
File I/O • IO.StreamReader class • Used for reading text files. Dim sr As IO.StreamReader sr = IO.File.OpenText(“hello.txt”) The object sr is created and opened the file “hello.txt” for reading
File I/O • If the file does not exist, you get an exception • You need to “trap” the exception so the program does not fail. • There are different exceptions for different errors
File I/O • Reading text from the file • ReadLine method • Reads one complete line of text from the file • Read method • Reads at least one character from the file
File I/O • How do I know I finished reading a file? • Use the Peek method in the StreamReader • Peek returns -1 it you reached the end of the file
File I/O • Assume that there is a text file with the following format: id1 Last name1 First name1 Address1 City1 State1 Zip1 . . . idN Last nameN First nameN AddressN CityN StateN ZipN
File I/O • Let’s traverse the file and display it into a textbox with multilines
File I/O Dim sr As IO.StreamReader = IO.File.OpenText("members.txt") While sr.Peek <> -1 s = sr.ReadLine textbox1.text = textbox1.text & s EndWhile sr.Close()
File I/O • IO.StreamWriter class • Used for writing into text files. The object sr creates a new file (“hello.txt”) for writing Dim sr As IO.StreamWriter sr = IO.File.CreateText(“hello.txt”) The object sr opens a file (“hello.txt”) for appending text to it Dim sr As IO.StreamWriter sr = IO.File.AppendText(“hello.txt”)
File I/O • Writing text into the file • WriteLine method • Writes one complete line of text in the file and attaches a <return> (character 13) at the end of it • Write method • Writes at least one character in the file but does not attach a <return>
File I/O • Important!! • Make sure you call the Close method after you are done using the file. Dim sr As IO.StreamReader = IO.File.OpenText("members.txt") While sr.Peek <> -1 s = sr.ReadLine textbox1.text = textbox1.text & s EndWhile sr.Close() sr now closes the file