File handling

<< Previous: String methods Next: SQL >>

Opening a file

File handling refers to working with text files. When you open a file, it must be assigned to a variable. This is often known as the file handle.



Reading a file

You can read a line of a file by adding .readLine( ) to a file handle. Using the .endOfFile( ) method you can loop through an entire file. Both methods can be seen in the example below.



Writing to a file

You can use the .writeLine( ) command to write a line to the end of a text file.



Closing files

The .close( ) method is used to close a file. It is good practice to close a file as soon as you finish using it. So a program that read from a file at the start and wrote to it at the end would close the file inbetween the two tasks e.g. a highscore file in a game



Creating a textfile

To write to a new file it must first be created with the newFile( ) command.



Uses of textfiles

Text files are an effective way to store data between uses of a program. Some projects you might like to try include: Adding a high score to an existing quiz or game you have; Create a shopping list program with the ability to add items, remove them and clear the list

Knowledge check


Questions:
Correct:

Question text


<< Previous: String methods Next: SQL >>

© All materials created by and copyright S.Goff