- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
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
A MemoryStream
is a stream which works with data in a computer memory.
Option Strict On 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
We write six numbers to a memory with a 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 = 0
We set the position of the cursor in the stream to the beginning using the Position
property.
ms.WriteByte(9) ms.WriteByte(11) ms.WriteByte(6) ...
The WriteByte()
method writes a byte to the current stream at the current position.
Do While rs <> -1 Console.WriteLine(rs) rs = ms.ReadByte() Loop
Here we read all bytes from the stream and print them to the console.
ms.Close()
Finally, we close the stream.
$ ./memory.exe 9 11 6 8 3 7
Output of the example.
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 On 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
We have a file called languages. We read characters from that file and print them to the console.
Dim stream As StreamReader stream = New StreamReader(file)
The 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 languages Python Visual Basic PERL Java C C# $ ./readfile.exe Python Visual Basic PERL Java C C#
We have a languages file in the current directory. We print all lines of the file to the console.
In the next example, we will be counting lines.
Option Strict On 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
Counting lines in a file.
While Not (stream.ReadLine() Is Nothing) count += 1 End While
In the While loop, we read a line from the stream with the 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 On 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
In the preceding example, we write characters to the memory.
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.") swriter.Flush()
We write some text to the writer. The 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) Console.WriteLine(sreader.ReadToEnd())
Now we create an instance of the stream reader and read everything we have written back.
FileStream
A FileStream
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 On 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
We write some text in Russian azbuka to the file in the current working directory.
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. The XmlTextReader
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 On 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
This Visual Basic program reads data from the previously specified XML file and prints it to the terminal.
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.Element Console.Write(xreader.Name & ": ") Case XmlNodeType.Text Console.WriteLine(xreader.Value)
Here we print the element name and element text.
Catch e As XmlException Console.WriteLine("XML parse error")
We check for XML parse error.
$ ./readxml.exe language: Python language: Ruby language: Javascript language: C#
Output of example.
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 On 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
In the example, we create a cars file and write some car names into it.
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") sw.WriteLine("Skoda") ...
We write two lines to the stream.
Option Strict On 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
In the second example, we show other five shared methods of the File
class.
If File.Exists("cars")
The Exists()
method determines whether the specified file exists.
Console.WriteLine(File.GetCreationTime("cars")) Console.WriteLine(File.GetLastWriteTime("cars")) Console.WriteLine(File.GetLastAccessTime("cars"))
We get creation time, last write time and last access time of the specified file.
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 On 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
We will use two methods from the above mentioned object.
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 On 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
We use the 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 dirs Console.WriteLine(subDir.Name) Next
Here we loop through directories and print their names to the console.
For Each fileName In files Console.WriteLine(fileName) Next
Here we loop through the array of files and print their names to the console.
$ ./showcontents.exe newdir temp temporary ../io/append.exe ../io/append.vb ../io/append.vb~ ../io/author ../io/cars ...
Output of the example.
In this chapter, we have covered input & output operations in Visual Basic.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论