Recipe: Reading a file
Last updated at 5:05 am UTC on 30 August 2008
You want to read in a text file to the Squeak environment.
Create an instance of a CrLfFileStream on the file:
file := FileStream fileNamed: 'test.txt'.
Read the entire file into a String:
string := file contentsOfEntireFile.
Or alternatively process a line at a time:
[file atEnd] whileFalse:
[line := file nextLine. "Process the line"]
Look at the Stream protocol, and in Stream and PositionableStream. Please help fill in pages for these, if you can.
If you merely need to read the file, open File List and it will open in a Workspace.
Don't forget to close the stream when you're finished with it:
You can be sure that you close the file by using #ensure:
readmeFile := CrLfFileStream fileNamed: 'readme.txt'.
["Do stuff with readmeFile here"
string := readmeFile contentsOfEntireFile
] ensure: [readmeFile ifNotNil: [readmeFile close]].
How to create a file stream that opens a file in directory other than the current working dir, say c:\mytest.txt on Windows?
file := CrLfFileStream fileNamed: 'c:\mytest.txt'.
Aug 2008: updated and checked with version 3.10.2: OK. hjh
See also: Recipe: How to copy a file