In this episode, we’ll continue working with elements of the Finder. As we’ve learned, the Finder contains different elements such as disks and folders. Disks contain folders so we say that folders are elements of disks. Inside folders, we might find other folders or we might find files. Files, then, are elements of folders and share many of the same properties of folders such as name and size.
Files are also classes of the Finder. In fact, the Finder has several different classes of files. The two main classes are file and aliases. The difference between these two types of objects is slight, but crucial. An alias refers to an existing file and can maintain the link to the existing file even if you move or rename the file. This is the advantage of using aliases over files. A file object represents a specific file at a specific location on your system. If you need to reference an existing file, you should use alias because the Finder will maintain the link to that file if the file gets moved or renamed.
To create a new file in the Finder, we tell the Finder to make a new file with a specific name, just as we did with folders:
tell application "Finder" to make new file with properties{name: "test.txt"}
This code makes a new file named “test.txt” on your desktop. Now that we have an existing file object, we can get its alias and boss it around:
tell application "Finder" to set testAlias to alias "Macintosh HD:Users:yourusername:Desktop:test.txt"
Before running this code, make sure you have the correct path to the “test.txt” file. For example, if you changed the name of your main hard disk from “Macintosh HD” to “MacMac” and your username is “macdaddy”, then the path would be “MacMac:Users:macdaddy:Desktop:test.txt”. Run this code and look in the Result window. You should see the word “alias” in blue as the first word. This tells you that you now have an alias object. Remember, you can only use alias objects to refer to existing file objects. If you want to create new files, the you need to use the “make new file with properties” command.
In our next lesson, we’ll look at how to read data from and write data to a file.
In rb-appscript, we get the name of a file in a similar manner:
app('Finder').files.name.get
Note the explicit use of the word “get” to get the name of every file. Note, too, that rb-appscript returns an Array object that contain file names. An Array is a list of things. Here, the array is a list of strings. Each string represents the name of a file.
To make a new file, we use a similar syntax as we used with folders:
app('Finder').make(:new => :file, :with_properties => {:name => 'test2.txt'})
Leave a Reply