Squeak
  links to this page:    
View this PageEdit this PageUploads to this PageHistory of this PageTop of the SwikiRecent ChangesSearch the SwikiHelp Guide
Recipe: Reading a file
Last updated at 11:32 pm UTC on 6 July 2007
Problem
You want to read in a text file to the Squeak environment.

Solution
Create an instance of a FileStream on the file:

file := FileStream fileNamed: 'test.txt'.

Then you can do things like...

Process a line at a time:

[file atEnd] whileFalse:
[line := file nextLine. "Process the line"]

Or read the entire file into a String:

string := file contentsOfEntireFile.

Discussion
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:

file close.

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]].



Question 1
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'.
this will produce nil.

Question 2
How to copy a file to another folder?

FileDirectory new
copyFile: (FileStream readOnlyFileNamed: 'c:\\temp\fox.txt')
toFile: (FileStream readOnlyFileNamed: 'd:\\mydb\foxout.txt').

abouve code leads to an errer.

Thanks!
jimg1968

Answer2


FileDirectory new copyFileNamed: 'C:\myfile.txt' toFileNamed: 'd:\temp\AAprova.txt'.

EnricoSpinielli