We have already dealt with Exceptions in Selenium now we will focus on how to open/write/read to a text file. Further we would utilize the learning in our real life example of reading all the links on page and write it into a text file using Selenium.
Don’t forgot to like our FB page to learn more.
|Learn working with Files|
Important Tips for Reading a File:-
1.While working with files, we need to handle the Checked Exception in our code, otherwise our code will not compile.
2.FileReader class makes it possible to read the contents of a file as a stream of characters, thus we are using in our code to read characters from a text file.
3.BufferedReader class provides buffering to our FileReader. Rather than reading one character at a time from the file, we read a larger block at a time using BufferedReader.
We can specify the buffer size in the above case we have used the default size(8192 chars).
Incase we want sized buffer our code will look like this:-
4.ReadLine, method of BufferedReader Class, which reads a line of text. A line is considered to be terminated by any one of a line feed (‘n’), a carriage return (‘r’), or a carriage return followed immediately by a linefeed.
Important Tips for Writing into a File:-
1.FileWriter class makes it possible to write a file as a stream of characters, same like FileReader above.
2.Incase we want to control whether to append or overwrite into text file
By Default it is “False”, thus it will overwrite the existing data.
3.BufferedWriter class provides buffering to our Write. Rather than write one character at a time to the file, we write a larger block at a time. This is typically much faster, especially for disk access and larger data amounts
We can control the size of bufferedwriter like we did in bufferedreader class
4.We used File objects to obtain information about a file or directory.File object is used to obtain information about a particular file or directory and is not used to read or write data, like length of a file