Recipe: Reading a file
Last updated at 5:44 pm UTC on 22 May 2022
You want to read in a text file to the Squeak environment.
Create an instance of a MultiByteFileStream 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 FileList 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 := FileStream fileNamed: 'readme.txt'.
["Do stuff with readmeFile here"
string := readmeFile contentsOfEntireFile
] ensure: [readmeFile ifNotNil: [readmeFile close]].
Pharo: see http://www.deepintopharo.com/, chapter '3.3 Opening read and write streams'
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 := FileStream fileNamed: 'c:\mytest.txt'.
Aug 2008: updated and checked with version 3.10.2: OK. hjh
See also: Recipe: How to copy a file