Contents

Working with Files


The use of files is a requirement for many applications. This section resumes available facilities.

The following classes are needed to create and to access files:

Selecting an Existing File:

 | result |
result := StandardFileMenu
               oldFileFrom: (FileDirectory on: 'c:\windows\fonts').
result inspect

This opens a dialog window, that you should close with accept when you have made your selection:

The result of the dialog is either nil or an instance of StandardFileMenuResult.

Opening an Existing File:

To open the selected file, you can use the result and write:

 | fileStream |
fileStream := result directory
                   oldFileNamed: result name.

To load the contents of a graphics file, you can write:

  | result image fileStream |
result := StandardFileMenu
               oldFileFrom: (FileDirectory default).
result notNil
  ifTrue:
    [fileStream := result directory
                      oldFileNamed: result name.
     fileStream binary.
     image := ImageReadWriter formFromStream: fileStream.
     ^image
    ].

The ImageReadWriter automatically identifies the file format. Supported formats include *.bmp, *.gif, *.jpg, *.png and others.

Closing a File after Use

Files should be closed when they are completely processed. A recommended pattern for file use is:

 | fileStream |
fileStream := result directory
                   oldFileNamed: result name.
 <do the file processing here>
fileStream close.

or even better

 | fileStream |
fileStream := result directory
                   oldFileNamed: result name.
[<do the file processing here>]
    ensure: [fileStream close].

It is possible to save a Smalltalk image while a file is open. When the image is started again, Smalltalk tries to reopen all files that were left open when the image was saved. This will fail when

Work with Text Files

To create a new text file in your working directory, you write:

    | fileStream |
fileStream := FileDirectory default newFileNamed: 'textfile.txt'.
fileStream ascii.
  " write some lines of text into the file "
fileStream nextPutAll: 'This is the first line of text.'; cr.
fileStream nextPutAll: 'This is the second line of text.'; cr.
  " close the file "
fileStream close.

To read a text file line by line, you write:

    | fileStream line |
fileStream := FileDirectory default readOnlyFileNamed: 'textfile.txt'.
fileStream ascii.
  " read all lines of text into the file "
[fileStream atEnd]
  whileFalse:
    [line := aFileStream nextLine.
     Transcript show: line; cr.
    ].
  " close the file "
fileStream close.




Contents