Community Growth Web - Coeur d'Alene, ID

Girls Who Code - Get a File Loaded

Let's begin by working with the simplest means of data retrieval: reading from a text file. Text files can be used as a very simple database (you could store settings for a program, a list of high scores, numbers for a graph, etc.) or to simulate a more complex data source.

In order to create a text file, you can use any simple text editor. Windows Notepad or Mac OS X TextEdit will do; just make sure you format the file as “plain text.” It is also advisable to name the text files with the “.txt” extension, to avoid any confusion. And just as with image files, these text files should be placed in the sketch’s “data” directory in order for them to be recognized by the Processing sketch.

Once the text file is in place, Processing’s loadStrings() function is used to read the content of the file into a Stringarray. The individual lines of text in the file each become an individual element in the array. 

 

// This code will print all the lines from the source text file.
String[] lines = loadStrings("file.txt");
println("There are " + lines.length + " lines.");
printArray(lines);

To run the code, create a text file called “file.txt,” type a bunch of lines in that file, and place it in your sketch’s data directory.