Saltar para o conteúdo principal
Versão: 20 R5 BETA

File

File objects are created with the File command. Contêm referências a ficheiros de disco que podem ou não existir efectivamente no disco. 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

O exemplo seguinte cria um arquivo de preferências na pasta do projecto:

var $created : Boolean
$created:=File("/PACKAGE/SpecialPrefs/"+Current user+".myPrefs").create()

Pathnames

File objects support several pathnames, including filesystems or posix syntax. Supported pathnames are detailed in the Pathnames page.

Objeto File

.copyTo( destinationFolder : 4D.Folder { ; newName : Text } { ; overwrite : Integer } ) : 4D.File
copies the File object into the specified destinationFolder
.create() : Boolean
creates a file on disk according to the properties of the File object
.createAlias( destinationFolder : 4D.Folder ; aliasName : Text { ; aliasType : Integer } ) : 4D.File
creates an alias (macOS) or a shortcut (Windows)
.creationDate : Date
the creation date of the file
.creationTime : Time
the creation time of the file
.delete()
deletes the file
.exists : Boolean
true if the file exists on disk
.extension : Text
the extension of the file name (if any)
.fullName : Text
the full name of the file, including its extension (if any)
.getAppInfo() : Object
returns the contents of a .exe, .dll or .plist file information as an object
.getContent( ) : 4D.Blobreturns a 4D.Blob object containing the entire content of a file
.getIcon( { size : Integer } ) : Picture
the icon of the file
.getText( { charSetName : Text { ; breakMode : Integer } } ) : Text
.getText( { charSetNum : Integer { ; breakMode : Integer } } ) : Text

returns the contents of the file as text
.hidden : Boolean
true if the file is set as "hidden" at the system level
.isAlias : Boolean
true if the file is an alias, a shortcut, or a symbolic link
.isFile : Boolean
always true for a file
.isFolder : Boolean
always false for a file
.isWritable : Boolean
true if the file exists on disk and is writable
.modificationDate : Date
the date of the file's last modification
.modificationTime : Time
the time of the file's last modification
.moveTo( destinationFolder : 4D.Folder { ; newName : Text } ) : 4D.File
moves or renames the File object into the specified destinationFolder
.name : Text
the name of the file without extension (if any)
.open( { mode : Text } ) : 4D.FileHandle
.open( { options : Object } ) : 4D.FileHandle

creates and returns a new 4D.FileHandle object on the file, in the specified mode or with the specified options
.original : 4D.File
.original : 4D.Folder

the target element for an alias, a shortcut, or a symbolic link file
.parent : 4D.Folder
the parent folder object of the file
.path : Text
the POSIX path of the file
.platformPath : Text
the path of the file expressed with the current platform syntax
.rename( newName : Text ) : 4D.File
renames the file with the name you passed in newName and returns the renamed File object
.setAppInfo( info : Object )
writes the info properties as information contents of a .exe, .dll or .plist file
.setContent ( content : Blob )
rewrites the entire content of the file using the data stored in the content BLOB
.setText ( text : Text {; charSetName : Text { ; breakMode : Integer } } )
.setText ( text : Text {; charSetNum : Integer { ; breakMode : Integer } } )

writes text as the new contents of the file
.size : Real
the size of the file expressed in bytes

File

História
ReleaseMudanças
19 R4New HTTP Client log file constant
17 R5Adicionado

File ( path : Text { ; pathType : Integer }{ ; } ) : 4D.File
File (
fileConstant : Integer { ; } ) : 4D.File

ParâmetroTipoDescrição
pathText->Rota do arquivo
fileConstantInteger->Constante de arquivo 4D
pathTypeInteger->fk posix path (default) or fk platform path
-->* para devolver o arquivo da base de dados anfitriã
Resultados4D. File<-Novo objeto arquivo

Descrição

The File command creates and returns a new object of the 4D.File type. O comando aceita duas sintaxes:

File ( path { ; pathType } { ; * })

In the path parameter, pass a file path string. Pode utilizar uma string personalizada ou um sistema de ficheiros (por exemplo, "/DATA/myfile.txt").

Only absolute pathnames are supported with the File command.

Como padrão, 4D espera um caminho expresso com a sintaxe POSIX. If you work with platform pathnames (Windows or macOS), you must declare it using the pathType parameter. Estão disponíveis as seguintes constantes:

ParâmetrosValorComentário
fk platform path1Caminho expresso com uma sintaxe específica da plataforma (obrigatória em caso de caminho de plataforma)
fk posix path0Caminho expresso com a sintaxe POSIX (por padrão)

File ( fileConstant { ; * } )

In the fileConstant parameter, pass a 4D built-in or system file, using one of the following constants:

ParâmetrosValorComentário
Backup history file19Arquivo de histórico de cópias de segurança (ver Arquivos de configuração e rastreio). Armazenado na pasta de destino de cópia de segurança.
Backup log file13Arquivo atual do diário de backup. Armazenado na pasta Logs da aplicação.
Backup settings file1Arquivo padrão backup.4DSettings (formato xml), armazenado na pasta Settings do projecto
Backup settings file for data17backup.4DSettings file (formato xml) para o arquivo de dados, armazenado na pasta Settings da pasta de dados
Build application log file14Arquivo de registo atual em formato xml do construtor da aplicação. Armazenado na pasta Logs.
Build application settings file20Arquivo de configurações padrão do construtor da aplicação ("buildApp.4DSettings"). Armazenado na pasta Settings do projecto.
Compacting log file6Arquivo de registo da mais recente compactação feita com o comando Compact data file ou o centro de Manutenção e segurança. Armazenado na pasta Logs.
Current backup settings file18arquivo backup.4DSettings utilizado actualmente pela aplicação. Pode ser o arquivo de definições de backup (predefinido) ou um arquivo personalizado de definições de backup do usuário definido para o arquivo de dados
Debug log file12Log file created by the SET DATABASE PARAMETER(Debug log recording) command. Armazenado na pasta Logs.
Diagnostic log file11Log file created by the SET DATABASE PARAMETER(Diagnostic log recording) command. Armazenado na pasta Logs.
Directory file16directório.json, contendo a descrição dos usuários e grupos (se houver) para a aplicação do projecto. Pode ser localizado ou na pasta de configurações do usuário (por padrão, global ao projecto), ou na pasta de definições de dados (específica a um arquivo de dados).
HTTP Client log file24Log file created by the HTTP SET OPTION(HTTP client log) command. Armazenado na pasta Logs.
HTTP debug log file9Log file created by the WEB SET OPTION(Web debug log) command. Armazenado na pasta Logs.
HTTP log file8Log file created by the WEB SET OPTION(Web log recording) command. Armazenado na pasta Logs.
IMAP Log file23Log file created by the SET DATABASE PARAMETER(IMAP Log) command. Armazenado na pasta Logs.
Last backup file2Last backup file, named \<applicationName>[bkpNum].4BK, stored at a custom location.
Last journal integration log file22Nome completo do último arquivo de registo de integração do diário (armazenado na pasta Logs da aplicação restaurada), se existir. Este arquivo é criado, em modo de auto-reparação, assim que ocorrer a integração de um arquivo de registo
Repair log file7Arquivo de registo das reparações da base de dados efetuadas na base de dados no Centro de Manutenção e Segurança (MSC). Armazenado na pasta Logs.
Request log file10Standard 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. Se executado no servidor, o ficheiro de registo do servidor é devolvido (armazenado na pasta Logs do servidor). Se executado no cliente, o arquivo de registo do cliente é devolvido (armazenado na pasta local Logs do cliente).
SMTP log file15Log file created by the SET DATABASE PARAMETER(SMTP Log) command. Armazenado na pasta Logs.
User settings file3settings.4DSettings arquivo para todos os arquivos de dados, guardados na pasta Preferências ao lado do arquivo de estrutura, se ativado.
User settings file for data4arquivo settings.4DSettings para dados atual, guardado na pasta Preferências ao lado do arquivo de dados.
Verification log file5Log files created by the VERIFY CURRENT DATA FILE and VERIFY DATA FILE commands or the Maintenance and Security Center (MSC). Armazenado na pasta Logs.

If the target fileConstant does not exist, a null object is returned. Não se levantam erros.

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ória
ReleaseMudanças
18 R6Adicionado

4D.File.new ( path : Text { ; pathType : Integer }{ ; * } ) : 4D.File
4D.File.new ( fileConstant : Integer { ; * } ) : 4D.File

Descrição

The 4D.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 of 4D.File.new().

.copyTo()

História
ReleaseMudanças
17 R5Adicionado

.copyTo( destinationFolder : 4D.Folder { ; newName : Text } { ; overwrite : Integer } ) : 4D.File

ParâmetroTipoDescrição
destinationFolder4D. Folder->Pasta de destino
newNameText->Nome para a copia
overwriteInteger->fk overwrite to replace existing elements
Resultados4D. File<-Arquivo copiado

Descrição

The .copyTo() function copies the File object into the specified destinationFolder .

The destinationFolder must exist on disk, otherwise an error is generated.

Como padrão, o arquivo é copiado com o nome do arquivo original. If you want to rename the copy, pass the new 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.

If a file with the same name already exists in the destinationFolder, by default 4D generates an error. You can pass the fk overwrite constant in the overwrite parameter to ignore and overwrite the existing file

ParâmetrosValorComentário
fk overwrite4Sobrescrever os elementos existentes, se houver

Valor retornado

The copied File object.

Exemplo

You want to copy a picture file from the user's document folder to the application folder:

var $source; $copy : Object
$source:=Folder(fk documents folder).file("Pictures/photo.png")
$copy:=$source.copyTo(Folder("/PACKAGE");fk overwrite)

.create()

História
ReleaseMudanças
17 R5Adicionado

Not available for ZIP archives

.create() : Boolean

ParâmetroTipoDescrição
ResultadosParâmetros<-True se o arquivo foi criado com sucesso, false caso contrário

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. Se o arquivo já existir no disco, a função não faz nada (não é atirado nenhum erro) e retorna falso.

Valor retornado

  • True if the file is created successfully;
  • False if a file with the same name already exists or if an error occured.

Exemplo

Criação de um arquivo de preferências na pasta da base de dados:

 var $created : Boolean
$created:=File("/PACKAGE/SpecialPrefs/"+Current user+".myPrefs").create()

.createAlias()

História
ReleaseMudanças
17 R5Adicionado

.createAlias( destinationFolder : 4D.Folder ; aliasName : Text { ; aliasType : Integer } ) : 4D.File

ParâmetroTipoDescrição
destinationFolder4D. Folder->Pasta de destino para o pseudónimo ou atalho
aliasNameText->Nome do pseudónimo ou atalho
aliasTypeInteger->Tipo de ligação do pseudónimo
Resultados4D. File<-Referência a pseudónimo ou ficheiro de atalho

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.

Por padrão em macOS, a função cria um pseudónimo padrão. You can also create a symbolic link by using the aliasType parameter. Estão disponíveis as seguintes constantes:

ParâmetrosValorComentário
fk alias link0Alias link (padrão)
fk symbolic link1Link simbólico (só em macOS)

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

Se quiser criar um alias para um arquivo na sua pasta database:

 $myFile:=Folder(fk documents folder).file("Archives/ReadMe.txt")
$aliasFile:=$myFile.createAlias(File("/PACKAGE");"ReadMe")

.creationDate

História
ReleaseMudanças
17 R5Adicionado

.creationDate : Date

Descrição

The .creationDate property returns the creation date of the file.

This property is read-only.

.creationTime

História
ReleaseMudanças
17 R5Adicionado

.creationTime : Time

Descrição

The .creationTime property returns the creation time of the file (expressed as a number of seconds beginning at 00:00).

This property is read-only.

.delete()

História
ReleaseMudanças
17 R5Adicionado

.delete()

ParâmetroTipoDescrição
Não exige nenhum parâmetro

Descrição

The .delete() function deletes the file.

Se o arquivo não existir no disco, a função não faz nada (não é gerado nenhum erro).

Se o ficheiro estiver atualmente aberto, o resultado depende do sistema operativo:

  • no Windows, é gerado um erro,
  • no macOS, não é gerado qualquer erro e o ficheiro é eliminado.
caution

.delete() can delete any file on a disk. Isto inclui documentos criados com outras aplicações, bem como as próprias aplicações. .delete() should be used with extreme caution. A eliminação de um arquivo é uma operação permanente e não pode ser desfeita.

Exemplo

Se quiser apagar um ficheiro específico na pasta da base de dados:

 $tempo:=File("/PACKAGE/SpecialPrefs/"+Current user+".prefs")
If($tempo.exists)
$tempo.delete()
ALERT("User preference file deleted.")
End if

.exists

História
ReleaseMudanças
17 R5Adicionado

.exists : Boolean

Descrição

The .exists property returns true if the file exists on disk, and false otherwise.

This property is read-only.

.extension

História
ReleaseMudanças
17 R5Adicionado

.extension : Text

Descrição

The .extension property returns the extension of the file name (if any). Uma extensão sempre começa com ".". Uma extensão sempre começa com "." A propriedade devolve uma string vazia se o nome do arquivo não tiver extensão.

This property is read-only.

.fullName

História
ReleaseMudanças
17 R5Adicionado

.fullName : Text

Descrição

The .fullName property returns the full name of the file, including its extension (if any).

This property is read-only.

.getAppInfo()

História
ReleaseMudanças
19Adicionado

.getAppInfo() : Object

ParâmetroTipoDescrição
ResultadosObject<-Conteúdo do arquivo de versão recurso .exe/.dll ou .plist

Descrição

The .getAppInfo() function returns the contents of a .exe, .dll or .plist file information as an object.

A função deve ser utilizada com um arquivo .exe, .dll ou .plist existente. Se o arquivo não existir no disco ou não for um ficheiro .exe, .dll ou .plist válido, a função devolve um objecto vazio (não é gerado nenhum erro).

A função apenas é compatível com arquivos .plist em formato xml (baseado em texto). Um erro é retornado se usado com um arquivo .plist em formato binário.

Objeto devolvido com um arquivo .exe ou .dll

A leitura de um .exe ou .dll só é possível no Windows.

Todos os valores de propriedades são Texto.

PropriedadeTipo
InternalNameText
ProductNameText
CompanyNameText
LegalCopyrightText
ProductVersionText
FileDescriptionText
FileVersionText
OriginalFilenameText

Objeto devolvido com um arquivo .split

O conteúdo xml do arquivo é analisado e as chaves são devolvidas como propriedades do objeto, preservando os seus tipos (texto, booleano, número). .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.Copyright)

Veja também

.setAppInfo()

.getContent()

História
ReleaseMudanças
19 R2Returns 4D. Blob
17 R5Adicionado

.getContent( ) : 4D.Blob

ParâmetroTipoDescrição
Resultados4D. Blob<-Conteúdo do arquivo

Descrição

The .getContent() function returns a 4D.Blob object containing the entire content of a file. For information on BLOBs, please refer to the BLOB section.

Valor retornado

A 4D.Blob object.

Exemplo

To save a document's contents in a BLOB field:

 var $vPath : Text
$vPath:=Select document(""; "*"; "Select a document";0)
If(OK=1) //Se tiver sido escolhido um documento
[aTable]aBlobField:=File($vPath;fk platform path).getContent()
End if

.getIcon()

História
ReleaseMudanças
17 R5Adicionado

.getIcon( { size : Integer } ) : Picture

ParâmetroTipoDescrição
sizeInteger->Longitude de lado da imagem devolvida (píxeles)
ResultadosImagem<-Ícone

Descrição

The .getIcon() function returns the icon of the file.

The optional size parameter specifies the dimensions in pixels of the returned icon. 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.

Valor retornado

File icon picture.

.getText()

História
ReleaseMudanças
17 R5Adicionado

.getText( { charSetName : Text { ; breakMode : Integer } } ) : Text
.getText( { charSetNum : Integer { ; breakMode : Integer } } ) : Text

ParâmetroTipoDescrição
charSetNameText->Nome do conjunto de caracteres
charSetNumInteger->Número de conjuntos de caracteres
breakModeInteger->Modo de processamento para quebras de linha
ResultadosText<-Texto do documento

Descrição

The .getText() function returns the contents of the file as text .

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.

If the document contains a Byte Order Mark (BOM), 4D uses the character set that it has set instead of the one specified in charSetName or charSetNum (this parameter is then ignored). If the document does not contain a BOM and if charSetName or charSetNum is omitted, by default 4D uses the "UTF-8" character set.

In breakMode, you can pass a number indicating the processing to apply to end-of-line characters in the document. As seguintes constantes do tema "Documentos do Sistema" estão disponíveis:

ParâmetrosValorComentário
Document unchanged0Não processado
Document with native format1(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 CRLF2Quebras de linha são convertidas em formato Windows: CRLF (retorno de carro + quebra de linha)
Documento com CR3Quebras de linha são convertidas para o formato OS X: CR (retorno de carro)
Documento com LF4Quebras de linha são convertidas em formato Unix: LF (feed de linha)

By default, when you omit the breakMode parameter, line breaks are processed in native mode (1).

Valor retornado

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 por padrão
$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.

Aqui está outro exemplo com o mesmo arquivo, mas um delimitador de linha diferente:

 $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ória
ReleaseMudanças
17 R5Adicionado

.hidden : Boolean

Descrição

The .hidden property returns true if the file is set as "hidden" at the system level, and false otherwise.

This property is read/write.

.isAlias

História
ReleaseMudanças
17 R5Adicionado

.isAlias : Boolean

Descrição

The .isAlias property returns true if the file is an alias, a shortcut, or a symbolic link, and false otherwise.

This property is read-only.

.isFile

História
ReleaseMudanças
17 R5Adicionado

.isFile : Boolean

Descrição

The .isFile property returns always true for a file.

This property is read-only.

.isFolder

História
ReleaseMudanças
17 R5Adicionado

.isFolder : Boolean

Descrição

The .isFolder property returns always false for a file.

This property is read-only.

.isWritable

História
ReleaseMudanças
17 R5Adicionado

.isWritable : Boolean

Descrição

The .isWritable property returns true if the file exists on disk and is writable.

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.

This property is read-only.

Exemplo

 $myFile:=File("C:\\Documents\\Archives\\ReadMe.txt";fk platform path)
If($myFile.isWritable)
$myNewFile:=$myFile.setText("Added text")
End if

.modificationDate

História
ReleaseMudanças
17 R5Adicionado

.modificationDate : Date

Descrição

The .modificationDate property returns the date of the file's last modification.

This property is read-only.

.modificationTime

História
ReleaseMudanças
17 R5Adicionado

.modificationTime : Time

Descrição

The .modificationTime property returns the time of the file's last modification (expressed as a number of seconds beginning at 00:00).

This property is read-only.

.moveTo()

História
ReleaseMudanças
17 R5Adicionado

.moveTo( destinationFolder : 4D.Folder { ; newName : Text } ) : 4D.File

ParâmetroTipoDescrição
destinationFolder4D. Folder->Pasta de destino
newNameText->Nome completo do ficheiro movido
Resultados4D. File<-Arquivo movido

Descrição

The .moveTo() function moves or renames the File object into the specified destinationFolder.

The destinationFolder must exist on disk, otherwise an error is generated.

Por padrão, o arquivo mantém o seu nome quando é movido. 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ória
ReleaseMudanças
17 R5Adicionado

.name : Text

Descrição

The .name property returns the name of the file without extension (if any).

This property is read-only.

.open()

História
ReleaseMudanças
18 R6Adicionado

.open( { mode : Text } ) : 4D.FileHandle
.open( { options : Object } ) : 4D.FileHandle

ParâmetroTipoDescrição
modeText->Modo de abertura: "read", "write", "append"
optionsObject->Opções de abertura
Resultados4D.FileHandle<-Novo objeto File handle

Descrição

The .open() function creates and returns a new 4D.FileHandle object on the file, in the specified mode or with the specified options. You can use functions and properties of the 4D.FileHandle class to write, read, or append contents to the file.

If you use the mode (text) parameter, pass the opening mode for the file handle:

modeDescrição
"read"(Padrão) Cria um file handle para ler os valores do arquivo. Se o arquivo não existir em disco, um erro é retornado. Pode abrir quantos file handles quiser em modo "ler" no mesmo objeto File.
"write"Cria um file handle para escrever os valores no arquivo (começando no início do conteúdo do arquivo). Se o arquivo não existir em disco, é criado. Só se pode abrir um único file handle em modo "write" no mesmo objeto File.
"append"Cria um file handle para escrever os valores no arquivo (começando no fim do conteúdo do arquivo). Se o arquivo não existir em disco, é criado. Só se pode abrir um único file handle em modo "append" no mesmo objeto File.

The mode value is case sensitive.

If you use the options (object) parameter, you can pass more options for the file handle through the following properties (these properties can be read afterwards from the opened file handle object):

opçõesTipoDescriçãoPor padrão
.modeTextOpening mode (see mode above)"read"
.charsetTextConjunto de carateres utilizado para ler ou escrever no ficheiro. Utilizar o nome padrão do conjunto (por exemplo "ISO-8859-1" ou "UTF-8")"UTF-8"
.breakModeReadText ou NumberModo de tratamento das quebras de linha utilizadas na leitura do arquivo (veja abaixo)"native" ou 1
.breakModeWriteText ou NumberModo de processamento das quebras de linha utilizadas ao escrever no ficheiro (ver abaixo)"native" ou 1

A função substitui todos os delimitadores de fim de linha originais. Por defeito, é utilizado o delimitador nativo, mas é possível definir outro delimitador. The .breakModeRead and .breakModeWrite indicate the processing to apply to end-of-line characters in the document. Pode utilizar um dos seguintes valores (texto ou número):

Modo de interrupção no textoBreak mode em numérico (constante)Descrição
"native"1 (Document with native format)(Padrão) As quebras de linha são convertidas para o formato nativo do sistema operativo: LF (avanço de linha) no macOS, CRLF (retorno de carro + avanço de linha) no Windows
"crlf"2 (Document with CRLF)As quebras de linha são convertidas em CRLF (retorno de carro + avanço de linha), o formato predefinido do Windows
"cr"3 (Document with CR)As quebras de linha são convertidas em CR (carriage return), o formato padrão do Mac OS
"lf"4 (Document with LF)As quebras de linha são convertidas para LF (line feed), o formato padrão Unix e macOS

The break mode as text value is case sensitive.

Exemplo

Pretende criar um file handle para a leitura do ficheiro "ReadMe.txt":

var $f : 4D.File
var $fhandle : 4D.FileHandle

$f:=File("C:\\Documents\\Archives\\ReadMe.txt";fk platform path)
$fhandle:=$f.open("read")

.original

História
ReleaseMudanças
17 R5Adicionado

.original : 4D.File
.original : 4D.Folder

Descrição

The .original property returns the target element for an alias, a shortcut, or a symbolic link file. O elemento alvo pode ser:

  • um objeto File
  • um objeto folder

Para arquivos não-alias, a propriedade retorna o mesmo objeto de arquivo que o arquivo.

This property is read-only.

.parent

História
ReleaseMudanças
17 R5Adicionado

.parent : 4D.Folder

Descrição

The .parent property returns the parent folder object of the file. .

This property is read-only.

.path

História
ReleaseMudanças
17 R5Adicionado

.path : Text

Descrição

The .path property returns the POSIX path of the file. .

This property is read-only.

.platformPath

História
ReleaseMudanças
17 R5Adicionado

.platformPath : Text

Descrição

The .platformPath property returns the path of the file expressed with the current platform syntax.

This property is read-only.

.rename()

História
ReleaseMudanças
17 R5Adicionado

.rename( newName : Text ) : 4D.File

ParâmetroTipoDescrição
newNameText->Novo nome completo para o ficheiro
Resultados4D. File<-Ficheiro renomeado

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. Se já existir um ficheiro com o mesmo nome, é devolvido um erro.

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

Se quiser renomear "ReadMe.txt" em "ReadMe_new.txt":

 $toRename:=File("C:\\Documents\\Archives\\ReadMe.txt";fk platform path)
$newName:=$toRename.rename($toRename.name+"_new"+$toRename.extension)

.setAppInfo()

História
ReleaseMudanças
20Suporte de WinIcon
19Adicionado

.setAppInfo( info : Object )

ParâmetroTipoDescrição
infoObject->Propriedades para escrever no arquivo .plist ou o recurso versão do arquivo .exe/.dll

Descrição

The .setAppInfo() function writes the info properties as information contents of a .exe, .dll or .plist file.

A função deve ser utilizada com um arquivo .exe, .dll ou .plist existente. Se o ficheiro não existir no disco ou não for um ficheiro .exe, .dll ou .plist válido, a função não faz nada (não é gerado qualquer erro).

A função apenas é compatível com arquivos .plist em formato xml (baseado em texto). Um erro é retornado se usado com um arquivo .plist em formato binário.

info parameter object with a .exe or .dll file

A escrita de um arquivo .exe ou .dll só é possível no Windows.

Each valid property set in the info object parameter is written in the version resource of the .exe or .dll file. As propriedades disponíveis são (qualquer outra propriedade será ignorada):

PropriedadeTipoComentário
InternalNameText
ProductNameText
CompanyNameText
LegalCopyrightText
ProductVersionText
FileDescriptionText
FileVersionText
OriginalFilenameText
WinIconTextCaminho Posix do ficheiro .ico. Esta propriedade aplica-se apenas a ficheiros executáveis gerados por 4D.

For all properties except WinIcon, if you pass a null or empty text as value, an empty string is written in the property. Se passar um tipo de valor diferente de texto, este é transformado em string.

For the WinIcon property, if the icon file does not exist or has an incorrect format, an error is generated.

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. Qualquer nome chave é aceito. Os tipos de valores são preservados sempre que possível.

If a key set in the info parameter is already defined in the .plist file, its value is updated while keeping its original type. Outras chaves existentes no arquivo .plist são deixadas intocadas.

Para definir um valor de tipo de data, o formato a utilizar é uma string de carimbo temporal json formada em ISO UTC sem milissegundos ("2003-02-01T01:02:03Z") como no editor plist de Xcode.

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

.getAppInfo()

.setContent()

História
ReleaseMudanças
17 R5Adicionado

.setContent ( content : Blob )

ParâmetroTipoDescrição
contentBLOB->Novos conteúdos para o arquivo

Descrição

The .setContent( ) function rewrites the entire content of the file using the data stored in the content BLOB. For information on BLOBs, please refer to the BLOB section.

Exemplo

 $myFile:=Folder(fk documents folder).file("Archives/data.txt")
$myFile.setContent([aTable]aBlobField)

.setText()

História
ReleaseMudanças
19 R3Padrão para novos projectos: sem BOM e (macOS) LF para EOL
17 R5Adicionado

.setText ( text : Text {; charSetName : Text { ; breakMode : Integer } } )
.setText ( text : Text {; charSetNum : Integer { ; breakMode : Integer } } )

ParâmetroTipoDescrição
textText->Texto a armazenar no arquivo
charSetNameText->Nome do conjunto de caracteres
charSetNumInteger->Número de conjuntos de caracteres
breakModeInteger->Modo de processamento para quebras de linha

Descrição

The .setText() function writes text as the new contents of the file.

If the file referenced in the File object does not exist on the disk, it is created by the function. Quando o ficheiro já existir no disco, o seu conteúdo anterior é apagado, exceto se já estiver aberto, caso em que o seu conteúdo é bloqueado e é gerado um erro.

In text, pass the text to write to the file. Pode ser um texto literal ("my text"), ou um campo/variável texto 4D.

Opcionalmente, pode designar o conjunto de caracteres a utilizar para escrever o 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 uma marca de ordem de byte (BOM) existe para o conjunto de caracteres, 4D a insere no ficheiro a menos que o conjunto de caracteres usado contenha o sufixo "-no-bom" (por exemplo, "UTF-8-no-bom"). Se não especificar um conjunto de caracteres, por defeito 4D usa o conjunto de caracteres "UTF-8" sem 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:

ParâmetrosValorComentário
Document unchanged0Não processado
Document with native format1(Padrão) As quebras de linha são convertidas para o formato nativo do sistema operativo: LF (avanço de linha) no macOS, CRLF (retorno de carro + avanço de linha) no Windows
Documento com CRLF2As quebras de linha são convertidas em CRLF (retorno de carro + avanço de linha), o formato predefinido do Windows
Documento com CR3As quebras de linha são convertidas em CR (carriage return), o formato padrão do Mac OS
Documento com LF4As quebras de linha são convertidas para LF (line feed), o formato padrão Unix e macOS

By default, when you omit the breakMode parameter, line breaks are processed in native mode (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ória
ReleaseMudanças
17 R5Adicionado

.size : Real

Descrição

The .size property returns the size of the file expressed in bytes. Se o arquivo não existir em disco, o tamanho é 0.

This property is read-only.