Send to Printer

st4u

ST 4U 177: Opening Files in VA Smalltalk

January 4, 2012 11:30:05.552

Today's Smalltalk 4 You looks at opening and closing files in VA Smalltalk. If you have trouble viewing it here in the browser, you can also navigate directly to YouTube. To watch now, click on the image below:

Files.

If you have trouble viewing that directly, you can click here to download the video directly. If you need the video in a Windows Media format, then download that here.

You can also watch it on YouTube:


Today we'll look at opening external files from VA Smalltalk, and how to read/write them once you've done that. To start with, have a look at the application CfsStreams:

CfsStreams

This is where the classes and APIS for reading/writing files are defined in VA Smalltalk. We'll start using CfsReadWriteFileStream to open and write a small file:


"open a file for read/write - if it does not exist, create it"
file := CfsReadWriteFileStream open: 'myNewFile.txt'.
file nextPutAll: 'This is my test text'.
file cr.
file close.

The first line opens the file - after which you can use standard stream methods to read and write text. Here we are simply writing some text, a CR, and then closing the file. The two methods of interest to us here are #open: and #close. The first you send to the class to open the file; the second you always send to close it. Once the file is out there, we can read it, and inspect the results to see what's there:

"open for reading" file := CfsReadFileStream open: 'myNewFile.txt'. data := file upToEnd. file close. ^data.

Read a File

Again, note the use of #open: and #close. Finally, what about error handling? Say a file you want to read doesn't exist? Here's the standard way to check for errors on file handling in VA:


"with error handling"
(file := CfsReadFileStream open: 'someFileNotThere.txt') isCfsError
		ifTrue: [^self error: file message].

All we're doing here is raising an exception on the error; you can, of course, do whatever handling makes sense in that block. Next time we'll get into the Stream APIs that were brushed over here.

Need more help? There's a screencast for other topics like this which you may want to watch. Questions? Try the "Chat with James" Google gadget over in the sidebar.

Technorati Tags: , ,

Enclosures:
[st4u177-iPhone.m4v ( Size: 6705853 )]

posted by James Robertson

 Share Tweet This