这部分的内容相对于前面的几部分有趣很多,本文介绍的是获取文件夹和文件的路径,并进行一些简单的操作。


获取文件夹或文件的路径

在Java桌面应用编写时有一个FileChooser,在AppleScript中可以通过简单的两个单词来调出文件选择窗口。

脚本如下:


choose folder



然后选择一个文件夹(可以看到我们无法选择文件):

ios文件路径使用 苹果文件夹路径_User


在点击选取后,结果输出为该文件夹的路径:


alias "Macintosh HD:Users:apple:Desktop:AFNetworkingDemo:"



这里的冒号“:”相当于文件路径中的分割符号“/”。

这里的alias表示给出的是文件的ID,而不是文件本身的存储位置,这样使得该文件在被移动后脚本依然能够找到该文件的存储位置。

如果路径前面的是file或folder,则表示返回的路径是文件或文件夹本身的存储位置。

最后的一个冒号指出AFNetworkingDemo是一个文件夹。


选择文件的方法:


choose file



在选取一个文件后返回的是该文件的路径:


alias "Macintosh HD:Users:apple:Desktop:AFNetworkingDemo:podFile"



可以看到路径结尾是没有冒号的,也就是podFile是一个文件。

同样地,我们无法选取一个文件夹,只能选择一个文件。



打开文件或文件夹

通过调用Finder处理程序可以打开文件或文件夹。当然打开前,我们要获取文件或文件夹的路径。

例如:


(*
tell application "Finder"
	open folder "Macintosh HD:Users:apple:Desktop:objc.io: #1 Light View Controllers:"
end tell
*)

tell application "Finder"
	open alias "Macintosh HD:Users:apple:Desktop:objc.io: #1 Light View Controllers:"
end tell

这两种方法都可以打开#1 Light View Controllers文件夹。


打开文件同理,方法如下:


(*
tell application "Finder"
	open file "Macintosh HD:Users:apple:Desktop:AFNetworkingDemo:podFile"
end tell
*)

tell application "Finder"
	open alias "Macintosh HD:Users:apple:Desktop:AFNetworkingDemo:podFile"
end tell




当然我们可以将choose file / folder和open file/folder/alias结合来使用。这样就不需要我们手动去填充文件和文件夹的路径了。例如:


set filePath to choose file
tell application "Finder"
	open file filePath
end tell
filePath




将路径赋给变量

我们可以将路径的值赋给变量。例如:


tell application "Finder"
	set filePath to file "Macintosh HD:Users:apple:Desktop:AFNetworkingDemo:podFile"
end tell



结果输出如下:


document file "podFile" of folder "AFNetworkingDemo" of folder "Desktop" of folder "apple" of folder "Users" of startup disk of application "Finder"




这样的路径表示形式实现太难看了,不过可以a reference to指令将其优化。例如:


tell application "Finder"
	set filePath to a reference to file "Macintosh HD:Users:apple:Desktop:AFNetworkingDemo:podFile"
end tell



结果输出为:


file "Macintosh HD:Users:apple:Desktop:AFNetworkingDemo:podFile" of application "Finder"




而更好的方法是使用alias获取文件的ID而不是绝对位置:


set filePath to alias "Macintosh HD:Users:apple:Desktop:AFNetworkingDemo:podFile"



结果区输出为:


alias "Macintosh HD:Users:apple:Desktop:AFNetworkingDemo:podFile"




之前我们可以通过empty the trash指令来清空废纸篓,这里我们也可以将文件直接移动到废纸篓中:


tell application "Finder"
	move "Macintosh HD:Users:apple:Desktop:AFNetworkingDemo:podFile" to the trash
end tell



使用move to指令可以让Finder程序将你的文件移动到其它位置。