VB File Processing

advertisement
VB File Processing
The Process of Using a File
• The file must be opened.
• Data is either written to the file or read from
the file.
• When the application is finished using the
file, the file is closed.
Types of Text File
• Sequential text file
– HTML file, Email file, etc.
• Comma-Delimited file
– "s5","peter",3.5
– "s1","paul",3
– "s7","mary",2
• Random access file
x-sender: me@dchaolaptop
x-receiver: you@dchaolaptop
Received: from mail pickup service by dchaolaptop with Microsoft SMTPSVC;
Mon, 19 May 2003 11:27:02 -0700
From: <me>
To: <you@dchaolaptop>
Subject: testReply6
Date: Mon, 19 May 2003 11:27:01 -0700
Message-ID: <008e01c31e34$3d982660$0100007f@dchaolaptop>
MIME-Version: 1.0
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
X-Mailer: Microsoft CDO for Windows 2000
Thread-Index: AcMeND2WJSRAs2TDR6WvOdKh/HDlHA==
Content-Class: urn:content-classes:message
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2600.0000
X-OriginalArrivalTime: 19 May 2003 18:27:02.0053 (UTC)
FILETIME=[3DCDB550:01C31E34]
testreplyreply6
System.IO Namespace
•
•
•
•
•
•
Directory
File
StreamReader
StreamWriter
StringReader
StringWriter
Stream
• A stream is an abstraction of a sequence of
bytes, such as a file, an input/output device,
an inter-process communication pipe, or a
TCP/IP socket. The Stream class and its
derived classes provide a generic view of
these different types of input and output,
isolating the programmer from the specific
details of the operating system and the
underlying devices.
Creating a Sequential Text File
• Declare a System.IO.StreamWriter writer object:
– Dim myFile As System.IO.StreamWriter
• Create a file using System.IO.File.CreateText or
AppendText method.
– myFile=system.IO.File.CreateText(“c:\myTextFile.txt”)
• CreateText method returns a StreamWriter.
• If myTextFile.txt already exist, its contents will be erased
– myFile=system.IO.File. AppendText(“c:\myTextFile.txt”)
• If myTextFile.txt already exist, data will be appended to the end.
• Note: CreateText and AppendText return a StreamWriter object.
• Use writer object’s WriteLine method to write data.
– myFile.WriteLine(“test”)
– myFile.Write(“test”)
***create a new line
***does not create a new line
• Use writer object’s Close method to close the file.
– myFile.Close()
Creating a Text File
Imports System.IO
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim myFile As System.IO.StreamWriter
myFile = System.IO.File.CreateText("c:\myTextFile.txt")
myFile.Write(TextBox1.Text)
myFile.Close()
End Sub
Reading Files with StreamReader
• Declare a System.IO.StreamReader reader object:
– Dim myFile As System.IO.StreamReader
• Open the file using System.IO.File.OpenText method.
– myFile=system.IO.File.OpenText(“c:\myTextFile.txt”)
• Use system.IO.File.Exists(FileName) to test if file exists.
• Read Data
– myFile.ReadLine()
*** Read one line
– myFile.Read()
*** Read one character code. Use Chr
function to convert the code to character: chr(myFile.Read())
• ReadLine and Read methods automatically move the pointer.
• To detect the end of a file: MyFile.Peek=-1
– myFile.ReadToEnd()
*** read entire contents of a file.
• Use writer object’s Close method to close the file.
– myFile.Close()
Reading a Text File
Private Sub Button2_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs)
Handles Button2.Click
Dim myFile As System.IO.StreamReader
myFile = System.IO.File.OpenText("c:\myTextFile.txt")
TextBox1.Text = myFile.ReadToEnd()
myFile.Close()
End Sub
OpenFileDialog
• Properties
– Filter:
description|filter
• The description and the filter are separated with the pipe |
symbol.
– Text file (*.txt) | *.txt
– All files (*.*) | *.*
– Initial directory
– FileName
• Method:
– ShowDialog
OpenFileDialog Example
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
MessageBox.Show(OpenFileDialog1.FileName)
myFile = System.IO.File.OpenText(OpenFileDialog1.FileName)
TextBox1.Text = myFile.ReadToEnd
Else
MsgBox("no file selected")
End If
SaveFileDialog Example
Dim outFile As System.IO.StreamWriter
If documentName = "" Then
If saveFileDialog1.ShowDialog = DialogResult.OK Then
documentName = saveFileDialog1.FileName
End If
End If
outFile = System.IO.File.CreateText(documentName)
outFile.Write(TextBox1.Text)
outFile.Close()
DrawString: Print One Line of
Text
• System.Drawing.Graphics
– DrawString method arguments:
–
–
–
–
–
String to print
Font
Brush
X position
Y position
• The X, Y coordinates must be declared as Single
data type. X coordinate is the horizontal distance
across a line from the left edge, Y coordinate is the
distance from the top.
PrintDocument Control
• PrinterSetting property:
–
–
–
–
–
PrinterName
PrintToFile
MaximumPage
MinimumPage
PaperSize
• Method:
– Print *** The Print method will trigger the PrintPage
event
PrintDialog Control
• Use the PrintDialog to get the values for the
PrinterSetting property of the PrintDocument
control.
– PrintDialog1.Document = PrintDocument1
– PrintDialog1.ShowDialog()
– With PrintDocument1.PrinterSettings
–
.PrintToFile = PrintDialog1.PrinterSettings.PrintToFile
–
.MaximumPage = PrintDialog1.PrinterSettings.MaximumPage
–
.PrinterName = PrintDialog1.PrinterSettings.PrinterName
– End With
• Note: The PrintDialog’s Document property gets or sets a
value indicating the PrintDocument used to obtain
PrinterSetting.
PrintDocument Example
PrintDocument1.Print()
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object,
ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles
PrintDocument1.PrintPage
e.Graphics.DrawString(textbox1.text, New Font("courier",
18, FontStyle.Bold), Brushes.Black, 150, 80)
End Sub
Print and PrintPage Event
• The Print method of the PrintDocument
control will trigger the PrintPage event.
This event is fired once for each page to be
printed. After finishing printing one page,
we can use the PrintPageEventArgs’
HasMorePage property to inform the
PrintDocument whether there is more page
to print.
PrintPreviewDialog Control
• PrintPreviewDialog1.Document = PrintDocument1
• PrintPreviewDialog1.ShowDialog()
Print Multiple Lines
• Textbox’s MultiLine property is true.
• Textbox’s Lines property returns a string
array with each line as an element.
• The Y position must be increased by the
height of the font.
PrintPageEventArgs
• DrawString: Send a line of text to the
graphics page.
• Properties:
– MarginBounds.Left, top, bottom, etc.
– HasMorePage
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal
e As System.Drawing.Printing.PrintPageEventArgs) Handles
PrintDocument1.PrintPage
Dim fntPrintFont As New Font("Courier", 18)
Dim sngLineHeight As Single = fntPrintFont.GetHeight + 2
Dim sngXPos As Single = e.MarginBounds.Left
Dim sngYPos As Single = e.MarginBounds.Top
Dim tempArray() As String
tempArray = TextBox1.Lines
Dim line As Integer
For line = 0 To tempArray.GetUpperBound(0)
e.Graphics.DrawString(tempArray(line), fntPrintFont, Brushes.Black,
sngXPos, sngYPos)
sngYPos += sngLineHeight
Next
End Sub
Printing Multiple Pages
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As
System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
Static pageCount As Integer = 1
Static lineCount As Integer = 0
Dim fntPrintFont As New Font("Courier", 18)
Dim sngLineHeight As Single = fntPrintFont.GetHeight + 2
Dim sngXPos As Single = e.MarginBounds.Left
Dim sngYPos As Single = e.MarginBounds.Top
Dim counter As Integer
Dim tempArray() As String
tempArray = TextBox1.Lines
e.Graphics.DrawString("Page " & pageCount.ToString, fntPrintFont, Brushes.Black, sngXPos, sngYPos)
sngYPos += sngLineHeight
For counter = lineCount To tempArray.GetUpperBound(0)
e.Graphics.DrawString(tempArray(counter), fntPrintFont, Brushes.Black, sngXPos, sngYPos)
sngYPos += sngLineHeight
If sngYPos >= e.MarginBounds.Bottom Then
pageCount = pageCount + 1
lineCount = counter + 1
e.HasMorePages = True
Exit For
End If
Next
End Sub
A Few Notes
• The X, Y coordinates must be declared as Single
data type. X coordinate is the horizontal distance
across a line from the left edge, Y coordinate is the
distance from the top.
• Font object type and its properties and methods.
• Textbox’s Lines property returns a string array
with each line as an element.
• Why the pageCount and lineCount are declared as
Static?
Comma-Delimited File
• It stores each data item with a comma
separating each item and places double
quotes around string fields.
– “S5”, ”Peter”, 3.0
– “S1”, “Paul”, 2.5
Creating a Comma-Delimted File
• Imports System.IO
• Open the file for output:
– fileNumber = FreeFile()
– FileOpen(fileNumber, "c:\stdata.txt", OpenMode.Output)
• Note: FreeFile function returns a file number.
• Use WriteLine function to write a record to the file:
– WriteLine(fileNumber, TextBox1.Text, TextBox2.Text, CDbl(TextBox3.Text))
• Note: Assuming write a student record with CID, CNAme, and GPA fields.
• Use the FileCose function to close the file:
– FileClose(fileNumber)
• Note: OpenMode.Append
Reading a Comma-Delimted File
• Imports System.IO
• Open the file for input:
– fileNumber = FreeFile()
– FileOpen(fileNumber, "c:\stdata.txt", OpenMode.Input)
• Use Input function to read a field from the file:
– If Not EOF(fileNumber) Then
–
Input(fileNumber, TextBox1.Text)
–
Input(fileNumber, TextBox2.Text)
–
Input(fileNumber, TextBox3.Text)
–
Else
–
MsgBox("Reach EOF")
– End If
• Note: The Input function can read only one filed from the file at a time.
• Note: The EOF function detects the End of File condition.
•
Use the FileCose function to close the file:
– FileClose(fileNumber)
Sequentialy Accessing the Student File
to Compute Average GPA
Dim fileNumber, stCounter As Integer
Dim temp1, temp2 As String
Dim gpa, sumGpa As Double
fileNumber = FreeFile()
FileOpen(fileNumber, "c:\stdata.txt", OpenMode.Input)
Do While Not EOF(fileNumber)
Input(fileNumber, temp1)
Input(fileNumber, temp2)
Input(fileNumber, gpa)
sumGpa += gpa
stCounter += 1
Loop
MessageBox.Show(sumGpa / stCounter.ToString)
Create a File Processing
Application
• Use a form to display a customer record in
textboxes. This form has a MoveNext
button to show the next record.
• A form to enter new customer data.
Structures
• A user-defined data type to hold related fields.
–
–
–
–
–
–
–
–
–
Structure emp
Dim eid As String
Dim ename As String
Dim salary As Double
End Structure
Dim myEmp as emp
myEmp.eid=“e1”
myEmp.ename=“peter”
myEmp.salary=5000.00
• A structure may contain arrays as fields, but
cannot be declared with an initial size. Must
use a ReDim statement to declare the size.
Structure emp
–
Dim eid As String
–
Dim ename As String
–
Dim salary As Double
–
Dim dependent() As String
– End Structure
– Dim myEmp as emp
– ReDim myEmp.dependent(3)
• A structure may also contain methods.
– Structure emp
–
Dim eid As String
–
Dim ename As String
–
Dim salary As Double
–
Dim dependent() As String
–
Function tax(ByVal salary) As Double
–
tax = salary * 0.15
–
End Function
– End Structure
– Dim myEmp As emp
–
myEmp.salary = 1000
–
myEmp.tax(myEmp.salary)
Random-Access File
• Records in a random-access file do not have to
processed in sequence. A record can be retrieved
selectively.
• A random-access file can be opened for both
reading and writing.
• Each record in a random-a ccess file is identified
by a unique integer, the first record is record 1.
• The records in a random-access file must be the
same size.
Using a Structure to Create Record
• Structure emp
•
<VBFixedString(3)> Dim eid As String
•
<VBFixedString(10)> Dim ename As String
•
Dim salary As Double
•
Function tax(ByVal salary) As Double
•
tax = salary * 0.15
•
End Function
• End Structure
• Note: Use <VBFixedString(3)> to control string
size.
Opening a Random-Access File
• FileOpen(fileNumber, fileName,OpenMode,OpenAccess,
OpenShare, RecordLength)
• OpenMode: Random
• OpenAccess:ReadWrite
• OpenShare
• RecordLength
• Example:
– Dim MyEmp as Emp
– fileNumber = FreeFile()
– FileOpen(fileNumber, "c:\empRnd.txt", OpenMode.Random,
OpenAccess.ReadWrite, OpenShare.Default, Len(myEmp))
Writing a Record
• FilePut(FileNumber, Record, RecordNumber)
– myEmp.eid = TextBox1.Text
–
–
–
myEmp.ename = TextBox2.Text
myEmp.salary = CDbl(TextBox3.Text)
FilePut(fileNumber, myEmp, CInt(myEmp.eid.Substring(1)))
Note: Assuming EID is of this format: XNN.
Reading a Record
• FileGet(FileNumber, Record, RecordNumber)
– Dim recNumber As Integer
– recNumber = CInt(InputBox("Please enter empID: ").Substring(1))
–
FileGet(fileNumber, myEmp, recNumber)
–
TextBox1.Text = myEmp.eid
–
TextBox2.Text = myEmp.ename
–
TextBox3.Text = myEmp.salary.ToString
–
Random File Example
Dim fileNumber As Integer
Structure emp
<VBFixedString(3)> Dim eid As String
<VBFixedString(10)> Dim ename As String
Dim salary As Double
Function tax(ByVal salary) As Double
tax = salary * 0.15
End Function
End Structure
Dim myEmp As emp
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
fileNumber = FreeFile()
FileOpen(fileNumber, "c:\empRnd.txt", OpenMode.Random,
OpenAccess.ReadWrite, OpenShare.Default, Len(myEmp))
Writing and Reading
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
myEmp.eid = TextBox1.Text
myEmp.ename = TextBox2.Text
myEmp.salary = CDbl(TextBox3.Text)
FilePut(fileNumber, myEmp, CInt(myEmp.eid.Substring(1)))
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button2.Click
Dim recNumber As Integer
recNumber = CInt(InputBox("Please enter empID: ").Substring(1))
FileGet(fileNumber, myEmp, recNumber)
If myEmp.eid.Substring(0, 1) <> "e" Then
MsgBox("record not exist")
Else
TextBox1.Text = myEmp.eid
TextBox2.Text = myEmp.ename
TextBox3.Text = myEmp.salary.ToString
End If
End Sub
Sequential Access to a Random-Access File
Dim outString As String
Dim recNumber As Integer = 1
Do While Not EOF(fileNumber)
FileGet(fileNumber, myEmp, recNumber)
outString = outString & recNumber.ToString & myEmp.eid &
myEmp.ename & myEmp.salary.ToString & vbCrLf
recNumber += 1
Loop
MessageBox.Show(outString)
Note: Do While recNumber <= NumberOfRecords
Hashing
• RecordAddress = H(Key)
• H(Key)=Key Mod M
0 <= Key Mod M <= M – 1
1 <= 1 + Key Mod M <= M
Hashing Example
• Key Mod 8
–
–
–
–
–
–
–
H(1821) = 5
H(7115) = 3
H(2428) = 4
H(4750) = 6
H(1620) = 4 **** Collision
H(4692) = 4
H(4758) = 6
• Collision resolution:
– Linear probing
Inserting a Record
• H(Key)
• If space H(Key) available, insert into space
K(Key)
• Else check subsequent space until a free
space is found.
– *** How to detect the file is full?
Searching a Record
• Read record at H(Key)
• If no record at H(Key), then record not exist
• If record at H(Key) is the searched record,
then Found
• Else Search the next space until reach an
empty space.
Deleting a Record
• Search the record to be deleted.
• Change a field to a special deletion flag.
• Write it back to its original space with the
deletion flag.
Serialization
• The act of saving (serializing) an object
onto a storage medium and later
deserializing it from the storage medium to
recreate an object.
• BinaryFormatter:
– Serialize
– Deserialize
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
Dim fs As New FileStream("c:\testSerializing.dat", FileMode.Create)
Dim myArrayList As New ArrayList
myArrayList.Add("A")
myArrayList.Add("B")
myArrayList.Add(5)
myArrayList.Add(10)
Dim bf As New BinaryFormatter
bf.Serialize(fs, myArrayList)
fs.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim fs As New FileStream("c:\testSerializing.dat", FileMode.Open)
Dim myArrayList As New ArrayList
Dim bf As New BinaryFormatter
myArrayList = CType(bf.Deserialize(fs), ArrayList)
Dim obj As New Object
For Each obj In myArrayList
ListBox1.Items.Add(obj)
Next
End Sub
Download