Beginning REALbasic - From Novice To Professional (2006)
.pdf246 |
C H A P T E R 9 ■ P R O C E S S I N G T E X T F I L E S |
Once you set up a FolderItem reference, you can manipulate it in a number of ways using properties and methods that belong to the FolderItem class. For example, you can use FolderItem properties to get a file or folder’s name, and FolderItem methods to copy, move, or delete files and folders.
Specifying File or Folder Location
One way to establish a reference to a file or folder is to specify the path to the file. For example, to access a file that resides in the same folder as REALbasic, you could establish a file reference as shown in the following:
Dim TargetFile As FolderItem
TargetFile = GetFolderItem("Config.txt")
As you can see, if no path information is provided, REALbasic assumes the specified file resides in the same folder as REALbasic or the completed application. You can now reference the specified file within your program code as TargetFile. Similarly, to access the folder where REALbasic resides, specify "" in place of a filename, as you see in the following:
Dim TargetFolder As FolderItem
TargetFolder = GetFolderItem("")
To access a file or folder in a different location, you must tell REALbasic in what disk drive the file or folder resides and provide the path to the file or folder. One way to do this is to begin by referencing the disk drive where the file or folder resides, and then use the FolderItem class’s Child method.
To reference a specific disk drive, use the Volume function. Each disk drive to which a computer is connected is automatically assigned a volume number, starting with Volume(0), which represents the boot drive (for example, the disk drive where the operating system (OS) files have been installed).
The Child method provides REALbasic with the relative location of a file or folder. For example, the following statements point REALbasic to a file named Config.txt, which is located in a folder named Configuration on the computer’s boot drive.
Dim TargetFile As FolderItem
TargetFile = Volume(0).Child("Configuration").Child("Config.txt")
Another helpful property you may want to use is the Parent property, which can be used to specify a reference to a folder relative to a file or folder it contains. For example, the following statement establishes a reference to the parent folder of the REALbasic folder.
Dim TargetFile As FolderItem
TargetFile = GetFolderItem("").Parent
C H A P T E R 9 ■ P R O C E S S I N G T E X T F I L E S |
247 |
■Note Once you establish a file or folder reference, you can use any of the FolderItem class’s properties to get information about the specified file or folder. For example, the following code statements establish a reference to the REALbasic folder, and then display a pop-up dialog window that shows how many files are stored in that folder using the FolderItem class’s Count property.
Dim TargetFile As FolderItem TargetFile = GetFolderItem("")
MsgBox("There are " + Str(TargetFile.Count) + _ " files in REALbasic's folder")
Accessing Special Folders
Macintosh, Windows, and Linux all have certain special folders used by specific parts of the OS. For example, both Macintosh and Windows make use of special folders that represents the user’s Desktop. Likewise, Linux OSs also have certain folders that have special importance. Examples include each users’ /home folder and the /etc, /bin, and /lib folders.
REALbasic helps to make accessing special folders easier by providing a SpecialFolder object that gives you access to properties representing various special folders on Macintosh, Windows, and Linux. For example, the following code statements show how to set up a reference to the Desktop special folder on Macintosh, Windows, and Linux.
Dim TargetFolder As FolderItem
TargetFolder = SpecialFolder.Desktop
The major advantage of accessing special folders in this manner is you don’t have to know or specify the actual location of these folders. REALbasic takes care of determining this for you.
Using Open File and Folder Dialog Windows
In situations where you want to give the user the capability to specify which file an application should open, REALbasic provides you with access to a standard Open dialog window. You can call on the Open dialog window in two ways. The first way is to use the GetOpenFolderItem function, which you saw in Chapter 8, when you created the RB Picture Viewer. As a quick review, look at the following example.
■Note Both the GetOpenFolderItem and the OpenDialog class return a value of Nil if the user clicks Cancel instead of selecting a file.
248 |
C H A P T E R 9 ■ P R O C E S S I N G T E X T F I L E S |
Dim TargetFile As FolderItem TargetFile = GetOpenFolderItem("text") If TargetFile <> Nil Then
'Add code to open and process the selected file End If
In this example, the GetOpenFolderItem displays the Open dialog window, waits for the user to select a text file, and then returns a reference to the selected file. The other option open to you is the OpenDialog class. Using this class, you can create a highly customized Open dialog window by setting any of the following properties:
•Left. Together, with the Top property, specifies the location where the upper left-hand corner of the Open dialog window is displayed.
•Top. Together, with the Left property, specifies the location where the upper left-hand corner of the Open dialog window is displayed.
•InitialDirectory. Specifies the default directory opened by the Open dialog window.
•Filter. Specifies the types of files that can be opened.
•ActionButtonCaptain. Specifies the text displayed on the Action button.
•CancelButtonCaption. Specifies the text displayed on the Cancel button.
•Title. Specifies the text string displayed in the Open dialog window’s title bar.
•PromptText. Displays a text message.
The following example demonstrates how to work with the OpenDialog class.
Dim dlg as OpenDialog |
'Declare variable represening the OpenDialog |
|
Dim TargetFile as FolderItem 'Declare |
variable to represet a FolderItem |
|
dlg = New OpenDialog |
'Instantiate a |
OpenDialog object |
dlg.InitialDirectory = Volume(0).Child("Diary") 'Set default directory dlg.Title = "Select A Diary Entry" 'Specify a titlebar message dlg.Filter = "FileTypes1/TEXT" 'Specify accessable file types 'Customise text displayed on the Action button
dlg.ActionButtonCaption = "Open File"
TargetFile = dlg.ShowModal() |
'Display the Open dialog window |
If TargetFile <> Nil Then |
'Make sure the user selected a file |
'Open and process the selected file End If
Figure 9-2 demonstrates how the customized Open dialog window looks when this example is run.
C H A P T E R 9 ■ P R O C E S S I N G T E X T F I L E S |
249 |
Figure 9-2. A customized Open dialog window, as seen on Mac OS X
■Tip You cannot use the standard Open dialog window to select a folder. Instead, REALbasic provides you with access to the SelectFolder function and the SelectFolderDialog class. Instead of returning a reference to a selected file, the SelectFolder function and SelectFolderDialog class return a reference to the selected folder, unless the user clicks the Cancel button, in which case a value of Nil is returned. The SelectFolderDialog class supports the same set of properties as the SelectFileDialog class.
Verifying Path and File or Folder Existence
Things have a tendency to move around a lot on computers, especially on computers shared by two or more people. As a result, files and folders may not always be where you expect them. To guard against this possibility and to prevent errors from occurring, it is important for you to add checks to your program code that ensure a specified path is valid and a specified file or folder exists.
If either of these two conditions is true, REALbasic returns a value of Nil in place of the file or folder reference. You should always check for these.
Dim TargetFile As FolderItem
TargetFile = Volume(0).Child("Configuration").Child("Config.txt") If TargetFile <> Nil Then 'Ensure that the specified path is valid
If TargetFile.Exists = True Then 'Ensure that the specified file exists 'Insert code here to process file
End If End If
250 |
C H A P T E R 9 ■ P R O C E S S I N G T E X T F I L E S |
Deleting Files and Folders
Using the FolderItem class’s Delete method, you can delete any file or folder, as the following shows.
Dim TargetFile As FolderItem
If TargetFile <> Nil Then 'Ensure that the specified path is valid
If TargetFile.Exists = True Then 'Ensure that the specified file exists TargetFile = Volume(0).Child("Configuration").Child("Config.txt") TargetFile.Delete
End If End If
Be careful when deleting files and folders using the FolderItem class’s Delete method. Resources deleted this way are deleted and not sent to the Trash Bin.
■Tip Instead of deleting a file, you have the option of moving it into the special trash folder, where it can later be deleted or restored. To accomplish this, use the FolderItem class’s MoveFileTo method in conjunction with the Trash special folder, as shown in the following:
TargetFile = Volume(0).Child("Configuration").Child("Config.txt")
TargetFile.MoveFileTo(SpecialFolder.Trash)
Process Text Files
Once your application has created or opened a text file, you’ll want to do something with it. This means reading its contents, writing something to it, or, perhaps, just printing it, which is discussed in the section “Printing Files.”
Reading from Text Files
As you might expect, REALbasic provides a number of different ways of reading from text files. For example, you can read a file all at once or you can read and process it line by line. One way to read a text file is to use the TextInputStream’s ReadLine method, as you see in the following example.
Dim InputFile As |
FolderItem |
'Declare a variable representing the FolderItem object |
||
'Declare |
a variable |
representing the TextInputStream object |
||
Dim SourceStream |
As |
TextInputStream |
||
'Display |
the Open dialog window |
InputFile = GetOpenFolderItem("FileTypes1/PlainText")
C H A P T E R 9 ■ P R O C E S S I N G T E X T F I L E S |
251 |
If InputFile <> Nil Then 'Make sure the user did not click on Cancel
'Retrieve a reference to the TextInputStream SourceStream = InputFile.OpenAsTextFile
While Not SourceStream.EOF 'Loop until end-of-file is reached 'Write a line from the source file to the EditField
EditField2.Text = EditField2.Text + SourceStream.ReadLine + EndOfLine Wend
SourceStream.Close 'Close the file once it has been read
End If
As you can see, a FolderItem reference is established using the GetOpenFolderItem function. Then, a check is made to make sure the user did not click the Open dialog window’s Cancel button. Next, a reference to the TextInputStream is set up, using the FolderItems class’s OpenAsTextFile method. TextInputStream is responsible for copying text from the file to the application. This is accomplished using a While…Wend loop that repeatedly executes the ReadLine method, pulling in a line of text at a time. The While…Wend loop iterates until the file’s end-of-file marker is reached. Also, note, this example ends by executing the TextInputStream object’s Close method. This is a critical step that ensures the file is properly closed and made available to other applications.
Or, you can read a file in a single step, instead of processing it line by line, as the following shows. To do so, you use the TextInputStream class’s ReadAll method.
Dim InputFile As FolderItem 'Declare a Folderitem variable
'Declare variable representing a TextInputStream Dim SourceStream As TextInputStream
InputFile = GetOpenFolderItem("text/plain") 'Display the Open dialog
If InputFile <> Nil Then 'Make sure user did not click on Cancel
'Retrieve a reference to the TextInputStream SourceStream = InputFile.OpenAsTextFile
'Write the contents of the file into the EdifField EditField1.Text = SourceStream.ReadAll
SourceStream.Close 'Close the file once it has been read
End If
252 |
C H A P T E R 9 ■ P R O C E S S I N G T E X T F I L E S |
Writing to Text Files
The FolderItem class also provides you with methods for writing text to files. For example, using the AppendToTextFile method, you can add text to the end of any file. If you want to work with a new text file, you can use the CreateTextFile method instead. Both of these methods return a TextOutputStream object. This object provides access to methods you can use to write to the file. The following example shows how to write to a new text file using the CreateTextFile method.
'Declare a variable representing the FolderItem object Dim OutputFile As FolderItem
'Declare a varialbe representing the TextOutputStream object Dim OutputStream As TextOutputStream
'Display the Save dialog |
window |
|
OutputFile = GetSaveFolderItem("FileTypes1/PlainText", |
"untitled.txt") |
|
'Make sure the user did not click on the Cancel button |
|
|
If OutputFile <> Nil Then |
|
|
OutputStream = OutputFile.CreateTextFile 'Create a |
new text file |
|
'Write the contents of |
the EditField to the specified file |
|
OutputStream.WriteLine |
EditField1.Text |
|
OutputStream.Close 'Close the file once it has been read
End If
As you can see, this example uses the TextOutputStream object’s WriteLine method to write the contents of single line EditFields to a text file. The TextOutputStream object’s Close method is then executed as the final step of working with the file.
Working with Styled Text
REALbasic EditField controls provide you with the capability to handle both plain and styled text. Styled text is text that has been formatted in some manner. Using the EditField control, you can add word processing-like capabilities to any REALbasic application. All that’s required is to enable the EditField control’s Styled property.
Examples of styled text include text that has been underlined or text that has been made italic or bold. Styled text also includes text that consists of different fonts and font sizes. The EditField control provides a set of methods you can use to toggle off and on different font styles. For example, the following statement would toggle the display of text between bold and nonbold.
C H A P T E R 9 ■ P R O C E S S I N G T E X T F I L E S |
253 |
EditField1.ToggleSelectionBold
Likewise, the following two statements could be used to toggle between italic and underline font styles.
EditField1.ToggleSelectionItalic
EditField1.ToggleSelectionUnderline
In similar fashion, you can use the EditField control’s SelTextSize and SelTextFont properties to change the font size and font type of any selected text. For specific examples of how to work with EditField properties related to styled text, check out the RB Word Processor application in the section “Creating a REALbasic Word Processor.”
Reading Styled Text
The preceding examples showed how to read and write plain text files. However, if your application contains Styled text, you’ll need to use different methods to ensure the styled text is properly handled. For example, to read a file containing styled text, you need to use the FolderItem class’s OpenStyledEditField method to read it, as shown in the following.
'Declare variable representing the FolderItem object Dim SourceFile as FolderItem
SourceFile = GetOpenFolderItem("Text") |
'Display the Open dialog |
|
If SourceFile <> Nil Then |
'Make sure |
user did not click on Cancel |
'Read and copy the contents of the file into the EditField SourceFile.OpenStyledEditfield EditField1
End If
In this example, the contents of the text file selected by the user are read into an EditField control, preserving any styled text. Note, for this example to work, the EditField control’s Multiline and Styled properties must be enabled.
Writing Styled Text to Files
To write a file containing styled text to a file, you need to use the SaveStyledEditField method, as the following shows.
'Declare a variable representing the FolderItem object Dim SourceFile as FolderItem
'Display the Save dialog window
SourceFile = GetSaveFolderItem("plain/text","Untitled.rtf")
254 |
C H A P T E R 9 ■ P R O C E S S I N G T E X T F I L E S |
If SourceFile <> Nil Then 'Make sure the user did not click on Cancel
'Write the contents of the EditField to the specified text file SourceFile .SaveStyledEditField EditField1
End If
This example takes any styled text located in an EditField1 and writes it to a file, while preserving its format.
Saving Files
Once your application is done making changes to a text file, you’ll want to save it. To do so, you can use either the GetSaveFolderItem function or the SaveAsDialog class to display the standard Save As dialog window, which the user can then use to specify the name and location where the file should be saved.
To use the GetSaveFolderItem function, you need to specify the file type and a default name for the file. The file type should match the information stored in the application’s File Set Type. For example, the following code statements demonstrate how to display the standard Save As dialog window to enable the user to specify the name and location where the file should be stored.
Dim TargetFile As FolderItem
TargetFile = GetSaveFolderItem("text", "Untitled") If TargetFile <> Nil Then
'Insert code here to save file End If
Note, in this example, a default filename of Untitled was specified.
The SaveAsDialog class supports all the properties supported by the OpenDialog and SelectFolderDialog classes. In addition, the SaveAsDialog class also supports the
SuggestedFileName property, which you can use to provide the user with a suggested default name for the file being saved. See the following example.
Dim dlg as SaveAsDialog |
'Declare variable representing the SaveAsDialog |
||
Dim TargetFile as FolderItem 'Declare |
variable to represent |
a FolderItem |
|
dlg = New SaveAsDialog |
'Instantiate |
a SaveAsDialog object |
|
dlg.InitialDirectory = Volume(0).Child("Diary") 'Set default directory dlg.SuggestedFileName = "Untitled" 'Specify a default filename dlg.Title = "Save Diary File" 'Specify a titlebar message
'Customise text displayed on the Action and Cancel buttons dlg.ActionButtonCaption = "Save File" dlg.CancelButtonCaption = "Don't Save"
C H A P T E R 9 ■ P R O C E S S I N G T E X T F I L E S |
255 |
TargetFile = dlg.ShowModal()'Display the Open dialog window
If TargetFile <> Nil then 'Make sure the user selected a file 'Enter statement to save file
End If
Printing Files
In addition to opening, writing to, reading from, and saving files, REALbasic lets you print them. REALbasic also provides you with the capability to display a Page Setup dialog window to enable the user to specify printing preferences. REALbasic also lets you display a Print dialog, and to print both styled and nonstyled text. And, REALbasic provides you with the capability to print directly to the printer, without using the Print dialog at all.
Working with the Page Setup Dialog Window
You might want to use the Page Setup dialog window in any application you let the user create and print documents. In the section “Creating a REALbasic Word Processor,” you see it used in a word processor application.
To display and work with the Page Setup dialog window, shown in Figure 9-3, you need to define and instantiate a PrinterSetup object, which provides access to settings from the Page Setup dialog. You also want define a variable to store print settings provided by the Page Setup dialog. You can then display the dialog and assign its settings, as seen the following example.
Figure 9-3. Collecting user print settings using the Page Setup dialog window, as seen on Windows