4D already provides commands to handle files and folders, but what about new commands that take advantage of the power of object notation?
Objects have changed the way many 4D developers write code, making it more generic, flexible, easier, and faster. Now this wave of change is extended to files and folders. In this blog post, we’ll show you how easy it is to manipulate an object in order to retrieve the attributes of a file or folder (rather than calling several commands and storing the information in multiple variables). Things are getting a lot easier!
Handling folders
New 4D commands
A new Folder command has been added which lets you create a folder object from a constant, a POSIX path, or a platform path.
myFolder:=Folder(fk desktop folder)
myFolder:=Folder("/RESOURCES/Images")
myFolder:=Folder("c:\\Archives\\";Platform path)
New Folder object
The folder object provides properties and methods so you can create and manipulate folders.
Here’s a few examples of folder properties:
// Name
$name:=myFolder.name
// Modification date
$date:=myFolder.modificationDate
// Modification time
$time:=myFolder.modificationTime
And there’s methods available, too! You can create(), moveTo(), rename(), delete(), etc.
// Move to
myMoveTo:=myFolder.moveTo(destinationFolder)
// Rename
myRename:=myFolder.rename("NewName")
// Delete
myFolder.delete(Delete with contents)
// List of files in myFolder
colFiles:=myFolder.files()
Folder objects contain references to folders that may or may not already exist on disk. For example, when you execute the Folder method to create a new folder, a valid folder object is created but nothing is actually stored on disk until you call the create() method.
newFolder=Folder(fk documents folder).folder("Archives/2019")
$result:=newFolder.exists // return False
newFolder:=newFolder.create()
$result:=newFolder.exists // return True
Handling files
New 4D commands
We’ve also added a File command to create a file object from a constant, a POSIX path, or a platform path.
myFile:=File(User settings file)
myFile:=File("/RESOURCES/Images/picture.png")
myFile:=File(Structure file;fk platform path)
New file object
As with folders, the new file object lets you access the file attributes and manipulate files.
// Name
$name:=myFile.name
// Extension
$extension:=myFile.extension
// Creation date
$date:=myFile.creationDate
// Creation time
$time:=myFile.creationTime
Also like folders, files have methods, too. You can write and read the contents of a file, move it, delete it ,and so on.
// Create a file with
myFile.setText($text)
// Retrieve the content of the file
$text:=myFile.getText()
// Delete
myFile.delete()
For the full list of attributes and methods, check out the doc center.