Reading and Writing to File
Your application might need to be able to read data in from a file or write data out to a file.
This might be a way of importing data or text into your application or saving preferences, settings or the current state of the application when it is closed.
With LiveCode reading from and writing to files is very simple.
The URL Keyword
As explained in the lesson Working With Text containers are sources of information. One of the LiveCode container types is URL. A URL is a container for a file (or other resource), which is on the same system the application is running on, or on another system that's accessible via the Internet.
URLs in LiveCode are written like the URLs you see in a browser. You use the URL keyword to designate a URL, enclosing the URL's name in double quotes:
put field "Info" into URL "file:myfile.txt"
get URL "http://www.example.org/stuff/nonsense.html"
put URL "ftp://ftp.example.net/myfile" into field "Data"
Working with URL Contents
You use a URL like any other container. You can get the content of a URL or use its content in any expression. You can also put any data into a URL, putting data into a file that does not exist causes it to be created.
You can also use chunk expressions with URLs, as with any other type of container:
put field "Info" into line 1 of URL "file:myfile.txt
get word 10 to 15 of URL "file:myfile.txt"
The http Scheme
An http URL designates a document from a web server. Put this in the script of the Try button:
on mouseUp put URL "https://www.livecode.com" into field "text" end mouseUp
You may have to wait a moment or two for the result to load in the field.
When you use an http URL in an expression, LiveCode downloads the URL from the server and substitutes the downloaded data for the URL.
When you put something into an http URL, LiveCode uploads the data to the web server.
Create a stack with a field called "text" and a button called "Choose file". The script of the button asks the user to choose a file and then puts the contents of that file into the field.
on mouseUp ## Ask the user to choose a file answer file "Please choose a file" ## If the dialog is not cancelled put the path to the selected file into a variable ## Use the URL keyword to put the contents of the file into a field if the result is not "cancel" then put it into tFilename put url ("file:" & tFilename) into field "text" end if end mouseUp
Finding the Path to Common Folders
A very common task is saving a file to, or reading a file from, a standard location. You can use the specialFolderPath function to build paths to system related folder and standard locations such as the Documents folder, desktop, preferences or home directory.
put specialFolderPath("documents") & "/Test Doc.txt" into tFilePath
This command puts the full path to a file in the documents folder called "Text Doc.txt" into the variable tFilePath. You can then use that path to read from or write to the file.