06.01.2013 Views

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

330 <strong>Learning</strong> <strong>Processing</strong><br />

We are going <strong>to</strong> follow this model in this section, working with the simplest means of data retrieval:<br />

reading from a text fi le. Text fi les can be used as a very simple database (we could s<strong>to</strong>re settings for a<br />

program, a list of high scores, numbers for a graph, etc.) or <strong>to</strong> simulate a more complex data source.<br />

In order <strong>to</strong> create a text fi le, you can use any simple text edi<strong>to</strong>r. Windows Notepad or Mac OS X<br />

TextEdit will do, just make sure you format the fi le as “ plain text. ” It is also advisable <strong>to</strong> name the text<br />

fi les with the “ .txt ” extension, just <strong>to</strong> avoid any confusion. And just as with image fi les in Chapter 15,<br />

these text fi les should be placed in the sketch’s “ data ” direc<strong>to</strong>ry in order for them <strong>to</strong> be recognized by the<br />

<strong>Processing</strong> sketch.<br />

Once the text fi le is in place, <strong>Processing</strong> ’s loadStrings( ) function is used <strong>to</strong> read the content of the fi le in<strong>to</strong><br />

a String array. Th e individual lines of text in the fi le (see Figure 18.2) each become an individual element<br />

in the array.<br />

fi g 18.2<br />

String[] lines = loadStrings(" file.txt " );<br />

println( " there are " + lines.length + " lines " );<br />

for (int i = 0; i < lines.length; i + + ) {<br />

println(lines[i]);<br />

}<br />

To run the code, create a text fi le called “ fi le.txt ” , type a bunch of lines in that fi le, and place it in your<br />

sketch’s data direc<strong>to</strong>ry.<br />

Exercise 18-6: Rewrite Example 17-3 so that it loads the headlines from a text fi le.<br />

Text from a data fi le can be used <strong>to</strong> generate a simple visualization. In Example 18-2, loads data fi le<br />

shown in Figure 18.3 . Th e results of visualizing this data are shown in Figure 18.4 .<br />

fi g. 18.3 Contents of “Data.txt”<br />

This code will print all the lines from the<br />

source text fi le. Shown in Figure 18.2.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!