Reading From A File Line by Line
Reading From A File Line by Line
A file is a collection of data stored in computer memory with a specific name and a defined folder
path. A path is used to perform operations on the path of a file.
There are different types of files which are: TXT, PDF, DOC and DOCX.
Visual Basic allows us to get input from different types of files and it also allow us to write output to
different types of files. We will talk about text files only. Firstly, we create object of file reader to read
some text from a file we created. A file must exist before reading it because if it does not exist, an
empty file will be created.
There are many ways we can read from a file like, reading from a file line by line and reading a
delimited file.
We can only read from a file line by line if the file contains only one item per line. The read line
method reads the text, starting from the current position and continuing until the end of the line is
counted. Reading from a file depends on how the data is stored in a file. However, we must keep in
mind that there is a limited number of data values in a file, but we do not know how many values
there in a file. Therefore, we typically use a while loop that test for the end of the file when we
process a file.
STEP 1
To read from a file we use a data type object called streamreader which is from the inputoutput class
that can read stream of characters coming from memory location.
File specification identifies the file to be read. This establishes a communication link between the
computer and the disk drive for reading data from the disk drive.
STEP 2
Reading a data item from a file is done using the readline builtin function.
StrVar= readerVar.Readline.
The data can be assigned to a numeric variable, in that case we use Val function.
When streamReader is initialized an input marker is positioned at the beginning of the file, then if
you reach the end of the file the marker is moved to the next line. After the last line is read, the
marker is said to be at the end of the file. The StreamReader has a Boolean function called
Endofstream. The Endofstream is vital if a file contains an unknown number of items, and you want
to read all the information.
STEP 3
readVar.Close()
Do not make decisions about the contents of the file based on the name of the file.
Do not assume that the file is small enough to fit into memory.
Do not forget to handle exceptions that may occur while reading the file.