Input & Output
This chapter is dedicated to Input & Output in Visual Basic. The Input & Output in Visual Basic is based on streams.Streams are objects to work with Input/Output. 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. In Visual Basic, we have a
Stream
class, that is an abstract class for all streams. There are additional classes that derive from the Stream class and make the programming a lot easier. MemoryStream
AMemoryStream
is a stream which works with data in a computer memory. Option Strict OnWe write six numbers to a memory with a
Imports System.IO
Module Example
Sub Main()
Dim ms As Stream = New MemoryStream(6)
ms.WriteByte(9)
ms.WriteByte(11)
ms.WriteByte(6)
ms.WriteByte(8)
ms.WriteByte(3)
ms.WriteByte(7)
ms.Position = 0
Dim rs As Integer
rs = ms.ReadByte()
Do While rs <> -1
Console.WriteLine(rs)
rs = ms.ReadByte()
Loop
ms.Close()
End Sub
End Module
MemoryStream
. Then we read those numbers and print them to the console. Dim ms As Stream = New MemoryStream(6)The line creates and initializes a
MemoryStream
object with a capacity of six bytes. ms.Position = 0We set the position of the cursor in the stream to the beginning using the
Position
property. ms.WriteByte(9)The
ms.WriteByte(11)
ms.WriteByte(6)
...
WriteByte()
method writes a byte to the current stream at the current position. Do While rs <> -1Here we read all bytes from the stream and print them to the console.
Console.WriteLine(rs)
rs = ms.ReadByte()
Loop
ms.Close()Finally, we close the stream.
$ ./memory.exeOutput of the example.
9
11
6
8
3
7
StreamReader & StreamWriter
StreamReader
reads characters from a byte stream. It defaults to UTF-8 encoding. StreamWriter
writes characters to a stream in a particular encoding. Option Strict OnWe have a file called languages. We read characters from that file and print them to the console.
Imports System.IO
Module Example
Sub Main()
Dim file As String
file = "languages"
Try
Dim stream As StreamReader
stream = New StreamReader(file)
Console.WriteLine(stream.ReadToEnd())
Catch e As IOException
Console.WriteLine("Cannot read file.")
End Try
End Sub
End Module
Dim stream As StreamReaderThe
stream = New StreamReader(file)
StreamReader
takes a file name as a parameter. Console.WriteLine(stream.ReadToEnd())The
ReadToEnd()
method reads all characters to the end of the stream. $ cat languagesWe have a languages file in the current directory. We print all lines of the file to the console.
Python
Visual Basic
PERL
Java
C
C#
$ ./readfile.exe
Python
Visual Basic
PERL
Java
C
C#
In the next example, we will be counting lines.
Option Strict OnCounting lines in a file.
Imports System.IO
Module Example
Sub Main()
Dim file As String
Dim count As Integer
file = "languages"
Try
Dim stream As StreamReader
stream = New StreamReader(file)
While Not (stream.ReadLine() Is Nothing)
count += 1
End While
Catch e As IOException
Console.WriteLine("Cannot read file.")
End Try
Console.WriteLine("There are {0} lines", count)
End Sub
End Module
While Not (stream.ReadLine() Is Nothing)In the While loop, we read a line from the stream with the
count += 1
End While
ReadLine()
method. It returns a line from the stream or Nothing if the end of the input stream is reached. An example with
StreamWriter
follows. Option Strict OnIn the preceding example, we write characters to the memory.
Imports System.IO
Module Example
Sub Main()
Dim mstream As New MemoryStream()
Dim swriter As New StreamWriter(mstream)
swriter.Write("ZetCode, tutorials for programmers.")
swriter.Flush()
Dim sreader As New StreamReader(mstream)
Console.WriteLine(sreader.ReadToEnd())
sreader.Close()
End Sub
End Module
Dim mstream As New MemoryStream()A
MemoryStream
is created. Dim swriter As New StreamWriter(mstream)A
StreamWriter
class takes a memory stream as a parameter. This way, we are going to write to memory stream. swriter.Write("ZetCode, tutorials for programmers.")We write some text to the writer. The
swriter.Flush()
Flush()
clears all buffers for the current writer and causes any buffered data to be written to the underlying stream. Dim sreader As New StreamReader(mstream)Now we create an instance of the stream reader and read everything we have written back.
Console.WriteLine(sreader.ReadToEnd())
FileStream
AFileStream
class uses a stream on a file on the filesystem. This class can be used to read from files, write to files, open them and close them. Option Strict OnWe write some text in Russian azbuka to the file in the current working directory.
Imports System.IO
Imports System.Text
Module Example
Sub Main()
Dim fstream As New FileStream("author", FileMode.Append)
Dim bytes As Byte() = New UTF8Encoding().GetBytes("Фёдор Михайлович Достоевский")
fstream.Write(bytes, 0, bytes.Length)
fstream.Close()
End Sub
End Module
Dim fstream As New FileStream("author", FileMode.Append)A
FileStream
object is created. The second parameter is a mode, in which the file is opened. The append mode opens the file if it exists and seeks to the end of the file, or creates a new file. Dim bytes As Byte() = New UTF8Encoding().GetBytes("Фёдор Михайлович Достоевский")We create an array of bytes from text in russian azbuka.
fstream.Write(bytes, 0, bytes.Length)We write the bytes to the file stream.
XmlTextReader
We can use streams to read xml data. TheXmlTextReader
is the class to read xml files in Visual Basic. The class is forward-only and read-only. We have the following xml test file.
<?xml version="1.0" encoding="utf-8" ?>
<languages>
<language>Python</language>
<language>Ruby</language>
<language>Javascript</language>
<language>C#</language>
</languages>
Option Strict OnThis Visual Basic program reads data from the previously specified xml file and prints it to the terminal.
Imports System.IO
Imports System.Xml
Module Example
Sub Main()
Dim file As String
file = "languages.xml"
Try
Dim xreader As New XmlTextReader(file)
xreader.MoveToContent()
Do While xreader.Read()
Select Case xreader.NodeType
Case XmlNodeType.Element
Console.Write(xreader.Name & ": ")
Case XmlNodeType.Text
Console.WriteLine(xreader.Value)
End Select
Loop
xreader.Close()
Catch e As IOException
Console.WriteLine("Cannot read file.")
Catch e As XmlException
Console.WriteLine("XML parse error")
End Try
End Sub
End Module
Dim xreader As New XmlTextReader(file)An
XmlTextReader
object is created. It takes the file name as a parameter. xreader.MoveToContent()The
MoveToContent()
method moves to the actual content of the xml file. Do While xreader.Read()This line reads the next node from the stream.
Case XmlNodeType.ElementHere we print the element name and element text.
Console.Write(xreader.Name & ": ")
Case XmlNodeType.Text
Console.WriteLine(xreader.Value)
Catch e As XmlExceptionWe check for xml parse error.
Console.WriteLine("XML parse error")
$ ./readxml.exeOutput of example.
language: Python
language: Ruby
language: Javascript
language: C#
Files and directories
The .NET framework provides other classes that we can use to work with files and directories.A
File
class is a higher level class that has shared methods for file creation, deletion, copying, moving and opening. These methods make the job easier. Option Strict OnIn the example, we create a cars file and write some car names into it.
Imports System.IO
Module Example
Sub Main()
Try
Dim sw As StreamWriter
sw = File.CreateText("cars")
sw.WriteLine("Toyota")
sw.WriteLine("Skoda")
sw.WriteLine("BMW")
sw.WriteLine("Volkswagen")
sw.WriteLine("Volvo")
sw.Close()
Catch e As IOException
Console.WriteLine("IO error")
End Try
End Sub
End Module
sw = File.CreateText("cars")The
CreateText()
method creates or opens a file for writing UTF-8 encoded text. It returns a StreamWriter
object. sw.WriteLine("Toyota")We write two lines to the stream.
sw.WriteLine("Skoda")
...
Option Strict OnIn the second example, we show other five shared methods of the File class.
Imports System.IO
Module Example
Sub Main()
If File.Exists("cars")
Console.WriteLine(File.GetCreationTime("cars"))
Console.WriteLine(File.GetLastWriteTime("cars"))
Console.WriteLine(File.GetLastAccessTime("cars"))
End If
File.Copy("cars", "newcars")
End Sub
End Module
If File.Exists("cars")The
Exists()
method determines whether the specified file exists. Console.WriteLine(File.GetCreationTime("cars"))We get creation time, last write time and last access time of the specified file.
Console.WriteLine(File.GetLastWriteTime("cars"))
Console.WriteLine(File.GetLastAccessTime("cars"))
File.Copy("cars", "newcars")The
Copy()
method copies the file. The
My.Computer.FileSystem
is and object, which provides properties and methods for working with drives, files, and directories. Option Strict OnWe will use two methods from the above mentioned object.
Imports System.IO
Module Example
Sub Main()
Try
My.Computer.FileSystem.CreateDirectory("temp")
My.Computer.FileSystem.CreateDirectory("newdir")
My.Computer.FileSystem.MoveDirectory("temp", "temporary")
Catch e As IOException
Console.WriteLine("Cannot create directories")
Console.WriteLine(e.Message)
End Try
End Sub
End Module
My.Computer.FileSystem.CreateDirectory("temp")The
CreateDirectory()
method creates a new directory. My.Computer.FileSystem.MoveDirectory("temp", "temporary")The
MoveDirectory()
method gives a specified directory a new name. The
DirectoryInfo
and Directory
have methods for creating, moving, and enumerating through directories and subdirectories. Option Strict OnWe use the
Imports System.IO
Module Example
Dim subDir As IO.DirectoryInfo
Dim dir As New IO.DirectoryInfo("../io")
Dim fileName As String
Dim files As String() = Directory.GetFiles("../io")
Dim dirs As DirectoryInfo() = dir.GetDirectories()
Sub Main()
For Each subDir In dirs
Console.WriteLine(subDir.Name)
Next
For Each fileName In files
Console.WriteLine(fileName)
Next
End Sub
End Module
DirectoryInfo
class to traverse a specific directory and print its contents. Dim dir As New IO.DirectoryInfo("../io")We will show the contents of this directory (io).
Dim files As String() = Directory.GetFiles("../io")We get all files of the io directory using the shared
GetFiles()
method. Dim dirs As DirectoryInfo() = dir.GetDirectories()We get all directories.
For Each subDir In dirsHere we loop through directories and print their names to the console.
Console.WriteLine(subDir.Name)
Next
For Each fileName In filesHere we loop through the array of files and print their names to the console.
Console.WriteLine(fileName)
Next
$ ./showcontents.exeOutput of the example.
newdir
temp
temporary
../io/append.exe
../io/append.vb
../io/append.vb~
../io/author
../io/cars
...
In this chapter, we have covered Input/Output operations in Visual Basic.
0 comments:
Post a Comment