File
File
objects are created with the File
command. They contain references to disk files that may or may not actually exist on disk. For example, when you execute the File
command to create a new file, a valid File
object is created but nothing is actually stored on disk until you call the file.create( )
function.
Exemplo
The following example creates a preferences file in the project folder:
var $created : Boolean
$created:=File("/PACKAGE/SpecialPrefs/"+Current user+".myPrefs").create()
File object
File
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
File ( path : Text { ; pathType : Integer }{ ; * } ) : 4D. File
File ( fileConstant : Integer { ; * } ) : 4D. File
Parameter | Type | Descrição | |
---|---|---|---|
path | Texto | -> | File path |
fileConstant | Integer | -> | 4D file constant |
pathType | Integer | -> | fk posix path (default) or fk platform path |
* | -> | * to return file of host database | |
Resultado | 4D. File | <- | New file object |
Descrição
The File
command creates and returns a new object of the 4D. File
type. The command accepts two syntaxes:
File ( path { ; pathType } { ; * })
In the path parameter, pass a file path string. You can use a custom string or a filesystem (e.g., "/DATA/myfile.txt").
Only absolute pathnames are supported with the
File
command.
By default, 4D expects a path expressed with the POSIX syntax. If you work with platform pathnames (Windows or macOS), you must declare it using the pathType parameter. The following constants are available:
Constante | Value | Comentário |
---|---|---|
fk platform path | 1 | Path expressed with a platform-specific syntax (mandatory in case of platform pathname) |
fk posix path | 0 | Path expressed with POSIX syntax (default) |
File ( fileConstant { ; * } )
In the fileConstant parameter, pass a 4D built-in or system file, using one of the following constants:
Constante | Value | Comentário |
---|---|---|
Backup history file | 19 | Backup history file (see Configuration and trace files). Stored in the backup destination folder. |
Backup log file | 13 | Current backup journal file. Stored in the application Logs folder. |
Backup settings file | 1 | Default backup.4DSettings file (xml format), stored in the Settings folder of the project |
Backup settings file for data | 17 | backup.4DSettings file (xml format) for the data file, stored in the Settings folder of the data folder |
Build application log file | 14 | Current log file in xml format of the application builder. Stored in the Logs folder. |
Build application settings file | 20 | Default settings file of the application builder ("buildApp.4DSettings"). Stored in the Settings folder of the project. |
Compacting log file | 6 | Log file of the most recent compacting done with the Compact data file command or the Maintenance and security center. Stored in the Logs folder. |
Current backup settings file | 18 | backup.4DSettings file currently used by the application. It can be the backup settings file (default) or a custom user backup settings file defined for the data file |
Debug log file | 12 | Log file created by the SET DATABASE PARAMETER(Debug log recording) command. Stored in the Logs folder. |
Diagnostic log file | 11 | Log file created by the SET DATABASE PARAMETER(Diagnostic log recording) command. Stored in the Logs folder. |
Directory file | 16 | directory.json file, containing the description of users and groups (if any) for the project application. It can be located either in the user settings folder (default, global to the project), or in the data settings folder (specific to a data file). |
HTTP debug log file | 9 | Log file created by the WEB SET OPTION(Web debug log) command. Stored in the Logs folder. |
HTTP log file | 8 | Log file created by the WEB SET OPTION(Web log recording) command. Stored in Logs folder. |
IMAP Log file | 23 | Log file created by the SET DATABASE PARAMETER(IMAP Log) command. Stored in the Logs folder. |
Last backup file | 2 | Last backup file, named <applicationName>[bkpNum].4BK, stored at a custom location. |
Last journal integration log file | 22 | Full pathname of the last journal integration log file (stored in the Logs folder of the restored application), if any. This file is created, in auto-repair mode, as soon as a log file integration occurred |
Repair log file | 7 | Log file of database repairs made on the database in the Maintenance and Security Center (MSC). Stored in the Logs folder. |
Request log file | 10 | Standard client/server request log file (excluding Web requests) created by the SET DATABASE PARAMETER(4D Server log recording) or SET DATABASE PARAMETER(Client log recording) commands. If executed on the server, the server log file is returned (stored in the Logs folder on the server). If executed on the client, the client log file is returned (stored in the client local Logs folder). |
SMTP log file | 15 | Log file created by the SET DATABASE PARAMETER(SMTP Log) command. Stored in the Logs folder. |
User settings file | 3 | settings.4DSettings file for all data files, stored in Preferences folder next to structure file if enabled. |
User settings file for data | 4 | settings.4DSettings file for current data file, stored in Preferences folder next to the data file. |
Verification log file | 5 | Log files created by the VERIFY CURRENT DATA FILE and VERIFY DATA FILE commands or the Maintenance and Security Center (MSC). Stored in the Logs folder. |
If the target fileConstant does not exist, a null object is returned. No errors are raised.
If the command is called from a component, pass the optional * parameter to get the path of the host database. Otherwise, if you omit the * parameter, a null object is always returned.
4D. File.new()
Histórico
Versão | Mudanças |
---|---|
v18 R6 | Adicionado |
4D. File.new ( path : Text { ; pathType : Integer }{ ; * } ) : 4D. File
4D. File.new ( fileConstant : Integer { ; * } ) : 4D. File
Descrição
File.new() function creates and returns a new object of the 4D. File
type. It is identical to the File
command (shortcut).
It is recommended to use the
File
shortcut command instead of4D. File.new()
.
.copyTo()
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.copyTo( destinationFolder : 4D. Folder { ; newName : Text } { ; overwrite : Integer } ) : 4D. File
Parameter | Type | Descrição | |
---|---|---|---|
destinationFolder | 4D. Folder | -> | Pasta de destino |
newName | Texto | -> | Nome para a copia |
overwrite | Integer | -> | fk overwrite para substituir os elementos existentes |
Resultado | 4D. File | <- | Arquivo copiado |
Descrição
A função .copyTo()
copia o objeto do arquivo `` para o objeto de destino especificadodestinationFolder .
A destinationFolder deve existir em disco, senão um erro é gerado.
Como padrão, o arquivo é copiado com o nome do arquivo original. Se quiser renomear a cópia, passe o novo nome no parâmetro newName . O novo nome deve cumprir com as regras de nomenclatura (por exemplo, não deve conter caracteres como ":", "/", etc.), do contrário se devolve um erro.
Se já existir um arquivo com o mesmo nome em destinationFolder, por padrão 4D gera um erro. Pode passar a constante fk overwrite
no parâmetro overwrite para ignorar e sobrescriber o arquivo existente
Constante | Value | Comentário |
---|---|---|
fk overwrite | 4 | Overwrite existing elements, if any |
Returned value
O objeto File
copiado.
Exemplo
Se quiser copiar um arquivo Imagem da pasta de documentos do usuário a pasta da aplicação:
var $source; $copy : Object
$source:=Folder(fk documents folder).file("Pictures/photo.png")
$copy:=$source.copyTo(Folder("/PACKAGE");fk overwrite)
.create()
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
Not available for ZIP archives
.create() : Boolean
Parameter | Type | Descrição | |
---|---|---|---|
Resultado | Booleano | <- | True if the file was created successfully, false otherwise |
Descrição
The .create()
function creates a file on disk according to the properties of the File
object.
If necessary, the function creates the folder hierachy as described in the platformPath or path properties. If the file already exists on disk, the function does nothing (no error is thrown) and returns false.
Returned value
- True if the file is created successfully;
- False if a file with the same name already exists or if an error occured.
Exemplo
Creation of a preferences file in the database folder:
var $created : Boolean
$created:=File("/PACKAGE/SpecialPrefs/"+Current user+".myPrefs").create()
.createAlias()
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.createAlias( destinationFolder : 4D. Folder ; aliasName : Text { ; aliasType : Integer } ) : 4D. File
Parameter | Type | Descrição | |
---|---|---|---|
destinationFolder | 4D. Folder | -> | Destination folder for the alias or shortcut |
aliasName | Texto | -> | Name of the alias or shortcut |
aliasType | Integer | -> | Type of the alias link |
Resultado | 4D. File | <- | Alias or shortcut file reference |
Descrição
The .createAlias()
function creates an alias (macOS) or a shortcut (Windows) to the file with the specified aliasName name in the folder designated by the destinationFolder object.
Pass the name of the alias or shortcut to create in the aliasName parameter.
By default on macOS, the function creates a standard alias. You can also create a symbolic link by using the aliasType parameter. The following constants are available:
Constante | Value | Comentário |
---|---|---|
fk alias link | 0 | Alias link (default) |
fk symbolic link | 1 | Symbolic link (macOS only) |
On Windows, a shortcut (.lnk file) is always created (the aliasType parameter is ignored).
Returned object
A 4D. File
object with the isAlias
property set to true.
Exemplo
You want to create an alias to a file in your database folder:
$myFile:=Folder(fk documents folder).file("Archives/ReadMe.txt")
$aliasFile:=$myFile.createAlias(File("/PACKAGE");"ReadMe")
.creationDate
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.creationDate : Date
Descrição
A propriedade .creationDate
retornaa data de criação do arquivo.
Essa propriedade éapenas leitura.
.creationTime
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.creationTime : Time
Descrição
A propriedade .creationTime
retornaa hora de criação do arquivo (expresso como número de segundos a partir de 00:00).
Essa propriedade éapenas leitura.
.delete()
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.delete( )
| Parameter | Type | | Descrição | | --------- | ---- | | ------------------------------- | | | | | Does not require any parameters |
Descrição
The .delete()
function deletes the file.
If the file is currently open, an error is generated.
If the file does not exist on disk, the function does nothing (no error is generated).
WARNING:
.delete( )
can delete any file on a disk. This includes documents created with other applications, as well as the applications themselves..delete( )
should be used with extreme caution. Deleting a file is a permanent operation and cannot be undone.
Exemplo
You want to delete a specific file in the database folder:
$tempo:=File("/PACKAGE/SpecialPrefs/"+Current user+".prefs")
If($tempo.exists)
$tempo.delete()
ALERT("User preference file deleted.")
End if
End if
.exists
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.exists : Boolean
Descrição
A propriedade .exists
retornatrue se o arquivo existir no disco, senão false.
Essa propriedade éapenas leitura.
.extension
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.extension : Text
Descrição
A propriedade .extension
retornaa extensão do nome do arquivo (se houver). An extension always starts with ".". The property returns an empty string if the file name does not have an extension.
Essa propriedade éapenas leitura.
.fullName
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.fullName : Text
Descrição
A propriedade .fullName
retornao nome completo do arquivo, incluindo a extensão (se houver).
Essa propriedade éapenas leitura.
.getAppInfo()
Histórico
Versão | Mudanças |
---|---|
v19 | Adicionado |
.getAppInfo() : Object
Parameter | Type | Descrição | |
---|---|---|---|
Resultado | Objeto | <- | Contents of .exe/.dll version resource or .plist file |
Descrição
The .getAppInfo()
function returns the contents of a .exe, .dll or .plist file information as an object.
The function must be used with an existing .exe, .dll or .plist file. If the file does not exist on disk or is not a valid .exe, .dll or .plist file, the function returns an empty object (no error is generated).
The function only supports .plist files in xml format (text-based). An error is returned if it is used with a .plist file in binary format.
Returned object with a .exe or .dll file
Reading a .exe or .dll is only possible on Windows.
All property values are Text.
Propriedade | Type |
---|---|
InternalName | Texto |
ProductName | Texto |
CompanyName | Texto |
LegalCopyright | Texto |
ProductVersion | Texto |
FileDescription | Texto |
FileVersion | Texto |
OriginalFilename | Texto |
Returned object with a .plist file
The xml file contents is parsed and keys are returned as properties of the object, preserving their types (text, boolean, number). .plist dict
is returned as a JSON object and .plist array
is returned as a JSON array.
Exemplo
// display copyright info of application .exe file (windows)
var $exeFile : 4D. File
var $info : Object
$exeFile:=File(Application file; fk platform path)
$info:=$exeFile.getAppInfo()
ALERT($info. LegalCopyright)
// display copyright info of an info.plist (any platform)
var $infoPlistFile : 4D. File
var $info : Object
$infoPlistFile:=File("/RESOURCES/info.plist")
$info:=$infoPlistFile.getAppInfo()
ALERT($info.
Veja também
.getContent()
Histórico
Versão | Mudanças |
---|---|
v19 R2 | Returns 4D. Blob |
v17 R5 | Adicionado |
.getContent( ) : 4D. Blob
Parameter | Type | Descrição | |
---|---|---|---|
Resultado | 4D. Blob | <- | Conteúdo do arquivo |
Descrição
The .getContent()
functionreturns a 4D. Blob
object containing the entire content of a file. Para informações sobre BLOBs, consultar a secção BLOB .
Returned value
A 4D. Blob
object.
Exemplo
Para salvar o conteúdo de um documento em um campo BLOB
:
var $vPath : Text
$vPath:=Select document("";"*";"Select a document";0)
If(OK=1) //If a document has been chosen
[aTable]aBlobField:=File($vPath;fk platform path).getContent()
End if
.getIcon()
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.getIcon( { size : Integer } ) : Picture
Parameter | Type | Descrição | |
---|---|---|---|
size | Integer | -> | Longitude de lado da imagem devolvida (píxeles) |
Resultado | Imagem | <- | Ícone |
Descrição
A função .getIcon()
retorna o ícone do arquivo.
O parâmetro opcional size especifica as dimensões em píxels do icone devolvido. Este valor representa em realidade a longitude do lado do quadrado que contém o icone. Icones são geralmente definidos como 32x32 píxels ('icones grandes') ou 16x16 ('icones pequenos'). Se passar 0 ou omitir este parâmetro, se devolve a versão 'icone grande'
Se o arquivo não existir no disco, um ícone em branco padrão será retornado.
Returned value
Ícone de arquivo imagem.
.getText()
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.getText( { charSetName : Text { ; breakMode : Integer } } ) : Text
.getText( { charSetNum : Integer { ; breakMode : Integer } } ) : Text
Parameter | Type | Descrição | |
---|---|---|---|
charSetName | Texto | -> | Nome do conjunto de caracteres |
charSetNum | Integer | -> | Número de conjuntos de caracteres |
breakMode | Integer | -> | Modo de processamento para quebras de linha |
Resultado | Texto | <- | Texto do documento |
Descrição
A função .getText()
retorna o conteúdo do arquivo como texto .
Opcionalmente, você pode designar o conjunto de caracteres a ser usado na leitura do conteúdo. Você pode passar também:
- in charSetName, a string containing the standard set name (for example "ISO-8859-1" or "UTF-8"),
- or in charSetNum, the MIBEnum ID (number) of the standard set name.
For the list of character sets supported by 4D, refer to the description of the
CONVERT FROM TEXT
command.
Se o documento contiver uma nota de ordem de byte (BOM), 4D usa o conjunto de caracteres que definiu em vez do especificado no charSetName ou charSetNum (este parâmetro é então ignorado). Se o documento não contiver uma LDM e se o charSetName ou charSetNum for omitido, por padrão 4D usa o conjunto de caracteres "UTF-8".
Em breakMode, você pode passar um número indicando o processamento a aplicar aos caracteres de fim de linha no documento. As seguintes constantes do tema "Documentos do Sistema" estão disponíveis:
Constante | Value | Comentário |
---|---|---|
Document unchanged | 0 | Não processado |
Document with native format | 1 | (Padrão) As quebras de linha são convertidas para o formato nativo do sistema operacional: CR (retorno de carro) sob OS X, CRLF (retorno do carro + salto de linha) em Windows |
Documento com CRLF | 2 | Quebras de linha são convertidas em formato Windows: CRLF (retorno de carro + quebra de linha) |
Documento com CR | 3 | Quebras de linha são convertidas para o formato OS X: CR (retorno de carro) |
Documento com LF | 4 | Quebras de linha são convertidas em formato Unix: LF (feed de linha) |
Por padrão, ao omitir o parâmetro breakMode , as quebras de linha são processadas no modo nativo (1).
Returned value
Texto do arquivo.
Exemplo
Dado o seguinte documento de texto (os campos são separados por tabulações):
id name price vat
3 thé 1.06€ 19.6
2 café 1.05€ 19.6
Quando você executar este código:
$myFile:=Folder(fk documents folder).file("Billing.txt") //UTF-8 by default
$txt:=$myFile.getText()
... you get the following for $txt
:
"id\tname\tprice\tvat\r\n3\tthé\t1.06€\t19.6\r\n2\tcafé\t1.05€\t19.6"
with \t
(tab) as separator and \r\n
(CRLF) as line delimiter.
Here is another example with the same file, but a different line delimiter:
$txt:=$myFile.getText("UTF-8", Document with LF)
In this case, the contents of $txt
are as follows:
"id\tname\tprice\tvat\n3\tthé\t1.06€\t19.6\n2\tcafé\t1.05€\t19.6"
This time \n
(LF) is used as line delimiter.
.hidden
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.hidden : Boolean
Descrição
A propriedade .hidden
devolve true se a pasta estiver como "escondida" ao nível do sistema, e falso em caso contrário.
Essa propriedade éapenas leitura.
.isAlias
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.isAlias : Boolean
Descrição
A propriedade .isAlias
devolve true se o arquivo for um alias, um atalho ou um link simbólico, e falso em caso contrário.
Essa propriedade éapenas leitura.
.isFile
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.isFile : Boolean
Descrição
A propriedade .isFile
retornasempre true para um arquivo.
Essa propriedade éapenas leitura.
.isFolder
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.isFolder : Boolean
Descrição
A propriedade .isFolder
retornasempre false para um arquivo.
Essa propriedade éapenas leitura.
.isWritable
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.isWritable : Boolean
Descrição
A propriedade .isWritable
retorna true se o arquivo existir em disco e é editável.
The property checks the ability of the 4D application to write on the disk (access rights), it does not solely rely on the writable attribute of the file.
Essa propriedade éapenas leitura.
Exemplo
$myFile:=File("C:\\Documents\\Archives\\ReadMe.txt";fk platform path)
If($myFile.isWritable)
$myNewFile:=$myFile.setText("Added text")
End if
.modificationDate
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.modificationDate : Date
Descrição
A propriedade .modificationDate
retorna a data da última modificação do arquivo.
Essa propriedade éapenas leitura.
.modificationTime
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.modificationTime : Time
Descrição
A propriedade .modificationTime
retornao tempo da última modificação do arquivo (expresso como um número de segundos começando às 00:00).
Essa propriedade éapenas leitura.
.moveTo()
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.moveTo( destinationFolder : 4D. Folder { ; newName : Text } ) : 4D. File
Parameter | Type | Descrição | |
---|---|---|---|
destinationFolder | 4D. Folder | -> | Pasta de destino |
newName | Texto | -> | Full name for the moved file |
Resultado | 4D. File | <- | Moved file |
Descrição
The .moveTo()
function moves or renames the File
object into the specified destinationFolder.
A destinationFolder deve existir em disco, senão um erro é gerado.
By default, the file retains its name when moved. If you want to rename the moved file, pass the new full name in the newName parameter. O novo nome deve cumprir com as regras de nomenclatura (por exemplo, não deve conter caracteres como ":", "/", etc.), do contrário se devolve um erro.
Returned object
The moved File
object.
Exemplo
$DocFolder:=Folder(fk documents folder)
$myFile:=$DocFolder.file("Current/Infos.txt")
$myFile.moveTo($DocFolder.folder("Archives");"Infos_old.txt")
.name
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.name : Text
Descrição
A propriedade .name
retorna o nome do arquivo sem extensão (se houver).
Essa propriedade éapenas leitura.
.original
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.original : 4D. File
.original : 4D. Folder
Descrição
A propriedade .original
retorna o elemento de destino para um alias, um atalho, ou um arquivo de link simbólico. The target element can be:
- a file object
- a folder object
For non-alias files, the property returns the same file object as the file.
Essa propriedade éapenas leitura.
.parent
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
Essa propriedade éapenas leitura.
Descrição
A propriedade .parent
retorna o objeto da pasta pai do arquivo. A função .folder()
<!-- REF #directory.folder().
Essa propriedade éapenas leitura.
.path
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.path : Text
Descrição
A propriedade .path
retorna o caminho POSIX do arquivo. If the path represents a filesystem (e.g., "/DATA/"), the filesystem is returned.
Essa propriedade éapenas leitura.
.platformPath
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.platformPath : Text
Descrição
A propriedade .platformPath
retorna o caminho do arquivo expresso com a sintaxe atual da plataforma.
Essa propriedade éapenas leitura.
.rename()
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.rename( newName : Text ) : 4D. File
Parameter | Type | Descrição | |
---|---|---|---|
newName | Texto | -> | New full name for the file |
Resultado | 4D. File | <- | Renamed file |
Descrição
The .rename()
function renames the file with the name you passed in newName and returns the renamed File
object.
The newName parameter must comply with naming rules (e.g., it must not contain characters such as ":", "/", etc.), otherwise an error is returned. If a file with the same name already exists, an error is returned.
Note that the function modifies the full name of the file, i.e. if you do not pass an extension in newName, the file will have a name without an extension.
Returned object
The renamed File
object.
Exemplo
You want to rename "ReadMe.txt" in "ReadMe_new.txt":
$toRename:=File("C:\\Documents\\Archives\\ReadMe.txt";fk platform path)
$newName:=$toRename.rename($toRename.name+"_new"+$toRename.extension)
.setAppInfo()
Histórico
Versão | Mudanças |
---|---|
v19 | Adicionado |
.setAppInfo( info : Object )
Parameter | Type | Descrição | |
---|---|---|---|
info | Objeto | -> | Properties to write in .exe/.dll version resource or .plist file |
Descrição
The .setAppInfo()
function writes the info properties as information contents of a .exe, .dll or .plist file.
The function must be used with an existing .exe, .dll or .plist file. The function must be used with an existing .exe, .dll or .plist file.
The function only supports .plist files in xml format (text-based). An error is returned if it is used with a .plist file in binary format.
info parameter object with a .exe or .dll file
Writing a .exe or .dll file information is only possible on Windows.
Each valid property set in the info object parameter is written in the version resource of the .exe or .dll file. Available properties are (any other property will be ignored):
Propriedade | Type |
---|---|
InternalName | Texto |
ProductName | Texto |
CompanyName | Texto |
LegalCopyright | Texto |
ProductVersion | Texto |
FileDescription | Texto |
FileVersion | Texto |
OriginalFilename | Texto |
If you pass a null or empty text as value, an empty string is written in the property. If you pass a value type different from text, it is stringified.
info parameter object with a .plist file
Each valid property set in the info object parameter is written in the .plist file as a key. Any key name is accepted. Value types are preserved when possible.
If a key set in the info parameter is already defined in the .plist file, its value is updated while keeping its original type. Other existing keys in the .plist file are left untouched.
To define a Date type value, the format to use is a json timestamp string formated in ISO UTC without milliseconds ("2003-02-01T01:02:03Z") like in the Xcode plist editor.
Exemplo
// set copyright and version of a .exe file (Windows)
var $exeFile : 4D. File
var $info : Object
$exeFile:=File(Application file; fk platform path)
$info:=New object
$info. LegalCopyright:="Copyright 4D 2021"
$info. ProductVersion:="1.0.0"
$exeFile.setAppInfo($info)
// set some keys in an info.plist file (all platforms)
var $infoPlistFile : 4D. File
var $info : Object
$infoPlistFile:=File("/RESOURCES/info.plist")
$info:=New object
$info. Copyright:="Copyright 4D 2021" //text
$info. ProductVersion:=12 //integer
$info. ShipmentDate:="2021-04-22T06:00:00Z" //timestamp
$infoPlistFile.setAppInfo($info)
Veja também
.setContent()
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.setContent ( content : Blob )
Parameter | Type | Descrição | |
---|---|---|---|
content | BLOB | -> | New contents for the file |
Descrição
The .setContent( )
function rewrites the entire content of the file using the data stored in the content BLOB. Para informações sobre BLOBs, consultar a secção BLOB .
Exemplo
$myFile:=Folder(fk documents folder).file("Archives/data.txt")
$myFile.setContent([aTable]aBlobField)
.setText()
Histórico
Versão | Mudanças |
---|---|
v19 R3 | Default for new projects: no BOM and (macOS) LF for EOL |
v17 R5 | Adicionado |
.setText ( text : Text {; charSetName : Text { ; breakMode : Integer } } )
.setText ( text : Text {; charSetNum : Integer { ; breakMode : Integer } } )
Parameter | Type | Descrição | ||
---|---|---|---|---|
texto | Texto | -> | Text to store in the file | |
charSetName | Texto | -> | Nome do conjunto de caracteres | |
charSetNum | Integer | -> | Número de conjuntos de caracteres | |
breakMode | Integer | -> | Processing mode for line breaks |
Descrição
|
If the file referenced in the File
object does not exist on the disk, it is created by the function. When the file already exists on the disk, its prior contents are erased, except if it is already open, in which case, its contents are locked and an error is generated.
In text, pass the text to write to the file. It can be a literal ("my text"), or a 4D text field or variable.
Optionally, you can designate the character set to be used for writing the contents. Você pode passar também:
- in charSetName, a string containing the standard set name (for example "ISO-8859-1" or "UTF-8"),
- or in charSetNum, the MIBEnum ID (number) of the standard set name.
For the list of character sets supported by 4D, refer to the description of the
CONVERT FROM TEXT
command.
If a Byte Order Mark (BOM) exists for the character set, 4D inserts it into the file unless the character set used contains the suffix "-no-bom" (e.g. "UTF-8-no-bom"). If you do not specify a character set, by default 4D uses the "UTF-8" character set without BOM.
In breakMode, you can pass a number indicating the processing to apply to end-of-line characters before saving them in the file. The following constants, found in the System Documents theme, are available:
Constante | Value | Comentário |
---|---|---|
Document unchanged | 0 | Não processado |
Document with native format | 1 | (Default) Line breaks are converted to the native format of the operating system: LF (line feed) on macOS, CRLF (carriage return + line feed) on Windows |
Documento com CRLF | 2 | Line breaks are converted to CRLF (carriage return + line feed), the default Windows format |
Documento com CR | 3 | Line breaks are converted to CR (carriage return), the default Classic Mac OS format |
Documento com LF | 4 | Line breaks are converted to LF (line feed), the default Unix and macOS format |
Por padrão, ao omitir o parâmetro breakMode , as quebras de linha são processadas no modo nativo (1).
Compatibility Note: Compatibility options are available for EOL and BOM management. See Compatibility page on doc.4d.com.
Exemplo
$myFile:=File("C:\\Documents\\Hello.txt";fk platform path)
$myFile.setText("Hello world")
.size
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.size : Real
Descrição
A propriedade .size
retorna o tamanho do arquivo expresso em bytes. If the file does not exist on disk, the size is 0.
Essa propriedade éapenas leitura.