(NEWBIE) FileStream help??

Tim Olson tim at jumpnet.com
Fri Apr 28 14:11:02 UTC 2000


James wrote:

>I'm trying to read from a file and output it to the Transcript window. The
>method I'm using works with Smalltalk Express but fails in Squeak can anyone
>look at this for me and tell me the problem please.
>
>Food class instance method:
>
>initializeFrom: aFile
>   | inputStream |
>   inputStream := File FileNamed: aFile.
>   self name: inputStream nextWord.
>   self fatCalories: inputStream nextWord asNumber.
>   self carbohydrateCalories: inputStream nextWord asNumber.
>   self proteinCalories: inputStream nextWord asNumber.
>   inputStream close.
>   ^self.

In Squeak, the term "word" in methods is mainly used to signify operating 
on a low-level memory word (2 bytes).  So "nextWord" is returning the 
next two bytes of the input stream treated as raw binary values, instead 
of what you are expecting (the next textual word).

There are a number of ways to do what you want.  One is to read each 
input line as a string, then use String's "findTokens" method:

     inputStream := File fileNamed: aFile.
     tokens := inputStream nextLine findTokens: Character separators.
     self name: tokens at: 1.
     self fatCalories: (tokens at: 2) asNumber.
     self carbohydrateCalories: (tokens at: 3) asNumber
     .
     .

Another way is to use Squeak's Smalltalk scanner to do the scanning and 
processing of the input stream for you.  This works well if your input 
token types match Smalltalk's (e.g. strings, numbers, etc.):

     inputStream := File fileNamed: aFile.
     scanner := Scanner new.
     scanner scan: inputStream.
     self name: scanner advance.
     self fatCalories: scanner advance.
     self carbohydrateCalories: scanner advance.

Note that the scanner does all of the work of converting the numeric 
tokens to numbers.





     -- tim






More information about the Squeak-dev mailing list