Tech Tip: The three ways to create a new file on the disk
PRODUCT: 4D | VERSION: 19 R | PLATFORM: Mac & Win
Published On: February 22, 2023
There are a few ways in 4D to directly create files on the disk, with each having their own set of benefits and drawbacks.
Create document command (before v17 R5)
The Create document command utilizes 4D’s classic commands before the arrival of File and Folder objects in v17 R5. When a file is created using this command, you must use the classic system document commands when handling the file.
Create document command
$path:=Get 4D folder(Database folder)+"Resources"+Folder separator+"createDocument.txt" Create document($path) |
File.create() function (after v17 R5)
The .create() function is one of many functions and properties offered under the File object. File objects allow for more versatility when handling system documents from the perspective of the file explorer. When it comes to handling the file’s content, you may only read or write its entire content. Moreover, the File class is a breeze to work with as it integrates easily with object-oriented programming.
.create() function
$path:=Get 4D folder(Database folder)+"Resources"+Folder separator+"createFile.txt" $file:=File($path; fk platform path) $created:=$file.create() |
Using file handles (after v19 R7)
Files can also be created on the disk using write and append file handles. Once a File object is created within 4D, a write or append handle can automatically create the file without having to use the .create() function mentioned earlier. This method is the most advantageous of the three, since file handles can also handle sections of the file content; this means the combination of File and FileHandle objects can allow you to work in both contexts outside and within the document.
Using write handle
$path:=Get 4D folder(Database folder)+"Resources"+Folder separator+"writeHandle.txt" $file:=File($path; fk platform path) $writeHandle:=$file.open("write") $writeHandle.writeLine("The quick brown fox jumps over the lazy dog.") |
Using append handle
$path:=Get 4D folder(Database folder)+"Resources"+Folder separator+"appendHandle.txt" $file:=File($path; fk platform path) $appendHandle:=$file.open("append") $appendHandle.writeLine("The quick brown fox jumps over the lazy dog.") |
Commented by Vincent de Lachaux on February 22, 2023 at 9:47 AM
More "modern":
$fileHdl:=File("/RESOURCES/appendHandle.txt").open("append")
$fileHdl.writeLine("The quick brown fox jumps over the lazy dog.")