Reading from Files 10 13 2010 Opening Discussion Midterm results Minute essay comments What are floats Motivation Programs are more useful when they can interact with files Everything that isn t in a file is lost when the program stops running I O Redirection Using I O redirection gives you some very basic ability to read from and write to files It has big limitations though because there is only one file each way More over that one file blocks the ability to use either standard input or output Packages and Imports To read from a file we will be using the scala io Source type To understand what that means we need to talk about packages Packages provide a way to organize code and group things of like functionality Import statements let you use things without typing in their fully specified names The API To get a sense of the different package in Scala it is helpful to look at the API There are still lots of things in the API you won t fully understand That isn t a problem as you aren t expected to get too much from it right now scala io Source Call Source fromFile fileName String to get a Source object that reads from a file There are other methods in the main Source object that we will learn about later The fromFile method technically gives you BufferedSource This is for efficiency Iterators Both Source and BufferedSource are of the type Iterator Char An Iterator has most of the methods you are used to from List and Array However you can only go through it once Fundamentally uses hasNext and next methods getLines This will give you an Iterator String that will go through the file one line at a time instead of a character at a time You will often find this more useful The split Method Even full lines isn t always what you want You might want multiple values for each line As you saw on the midterm the split method of String will break up the String on a delimiter and give you back an array Delimiter is regular expression Use for 1 or more and for 0 or more Let s try using this to get something useful Minute Essay What questions do you have Interclass problem Write a script that will read a file that x and y values for points on each line and print the shortest distance between any two points
View Full Document