Saltar al contenido principal
Versión: 20 R5 BETA

File

File objects are created with the File command. Contienen referencias a archivos de disco que pueden o no existir realmente en el 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.

Ejemplo

El siguiente ejemplo crea un archivo de preferencias en la carpeta del proyecto:

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

Rutas de acceso

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

Historia
LanzamientoModificaciones
19 R4New HTTP Client log file constant
17 R5Añadidos

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

ParámetrosTipoDescripción
pathText->Ruta del archivo
fileConstantInteger->Constante del archivo 4D
pathTypeInteger->fk posix path (default) or fk platform path
-->* para devolver el archivo de la base local
Result4D.File<-Nuevo objeto de archivo

Descripción

The File command creates and returns a new object of the 4D.File type. El comando acepta dos sintaxis:

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

In the path parameter, pass a file path string. Puede utilizar una cadena personalizada o un filesystem (por ejemplo, "/DATA/myfile.txt").

Only absolute pathnames are supported with the File command.

Por defecto, 4D espera una ruta expresada con la sintaxis POSIX. If you work with platform pathnames (Windows or macOS), you must declare it using the pathType parameter. Las siguientes constantes están disponibles:

ConstanteValorComentario
fk platform path1Ruta expresada con una sintaxis específica de la plataforma (obligatoria en caso de nombre de ruta de plataforma)
fk posix path0Ruta expresada con sintaxis POSIX (por defecto)

File ( fileConstant { ; * } )

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

ConstanteValorComentario
Backup history file19Archivo de historial de copias de seguridad (ver Archivos de configuración y rastreo). Se almacena en la carpeta de destino de la copia de seguridad.
Backup log file13Archivo historial de copias de seguridad actual. Almacenado en la carpeta Logs de la aplicación.
Backup settings file1Archivo backup.4DSettings por defecto (formato xml), almacenado en la carpeta Settings del proyecto
Backup settings file for data17archivo backup.4DSettings del archivo de datos (formato xml), almacenado en la carpeta Settings de la carpeta data
Build application log file14Archivo de historial actual en formato xml del generador de aplicaciones. Almacenado en la carpeta Logs.
Build application settings file20Archivo de configuración por defecto del generador de aplicaciones ("buildApp.4DSettings"). Almacenado en la carpeta Settings del proyecto.
Compacting log file6Archivo de historial de la compactación más reciente realizada con el comando Compact data file o el Centro de seguridad y mantenimiento. Almacenado en la carpeta Logs.
Current backup settings file18archivo backup.4DSettings utilizado actualmente por la aplicación. Puede ser el archivo de configuración de la copia de seguridad (por defecto) o un archivo de configuración de la copia de seguridad personalizado por el usuario definido para el archivo de datos
Debug log file12Log file created by the SET DATABASE PARAMETER(Debug log recording) command. Almacenado en la carpeta Logs.
Diagnostic log file11Log file created by the SET DATABASE PARAMETER(Diagnostic log recording) command. Almacenado en la carpeta Logs.
Directory file16archivo directory.json, que contiene la descripción de los usuarios y grupos (si los hay) del proyecto. Puede situarse en la carpeta user settings (por defecto, se aplica a todo el proyecto), o en la carpeta data settings (específica para un archivo de datos).
HTTP Client log file24Log file created by the HTTP SET OPTION(HTTP client log) command. Almacenado en la carpeta Logs.
HTTP debug log file9Log file created by the WEB SET OPTION(Web debug log) command. Almacenado en la carpeta Logs.
HTTP log file8Log file created by the WEB SET OPTION(Web log recording) command. Almacenado en la carpeta Logs.
IMAP Log file23Log file created by the SET DATABASE PARAMETER(IMAP Log) command. Almacenado en la carpeta Logs.
Last backup file2Last backup file, named \<applicationName>[bkpNum].4BK, stored at a custom location.
Last journal integration log file22Nombre completo del último archivo de registro de integración del historial (almacenado en la carpeta Logs de la aplicación restaurada), si la hay. Este archivo se crea, en modo de reparación automática, tan pronto como se produce una integración de archivos de historial
Repair log file7Archivo de historial de las reparaciones realizadas en la base por el Centro de seguridad y mantenimiento (CSM). Almacenado en la carpeta 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. Si se ejecuta en el servidor, se devuelve el archivo de registro del servidor (almacenado en la carpeta Logs del servidor). Si se ejecuta en el cliente, se devuelve el archivo de registro del cliente (almacenado en la carpeta Logs local del cliente).
SMTP log file15Log file created by the SET DATABASE PARAMETER(SMTP Log) command. Almacenado en la carpeta Logs.
User settings file3archivo settings.4DSettings para todos los archivos de datos, almacenados en la carpeta Preferences junto a la estructura del archivo si está activado.
User settings file for data4archivo settings.4DSettings para el archivo de datos actual, almacenado en la carpeta Preferences junto al archivo de datos.
Verification log file5Log files created by the VERIFY CURRENT DATA FILE and VERIFY DATA FILE commands or the Maintenance and Security Center (MSC). Almacenado en la carpeta Logs.

If the target fileConstant does not exist, a null object is returned. No se produce ningún error.

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()

Historia
LanzamientoModificaciones
18 R6Añadidos

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

Descripción

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()

Historia
LanzamientoModificaciones
17 R5Añadidos

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

ParámetrosTipoDescripción
destinationFolder4D.Folder->Carpeta de destino
newNameText->Nombre para la copia
overwriteInteger->fk overwrite to replace existing elements
Result4D.File<-Archivo copiado

Descripción

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

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

Por defecto, el archivo se copia con el nombre del archivo original. If you want to rename the copy, pass the new name in the newName parameter. El nuevo nombre debe cumplir con las reglas de nomenclatura (por ejemplo, no debe contener caracteres como ":", "/", etc.), de lo contrario se devuelve un error.

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

ConstanteValorComentario
fk overwrite4Sobrescribir los elementos existentes, si los hay

Valor devuelto

El objeto File copiado.

Ejemplo

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()

Historia
LanzamientoModificaciones
17 R5Añadidos

Not available for ZIP archives

.create() : Boolean

ParámetrosTipoDescripción
ResultBoolean<-True si el archivo se ha creado con éxito, false en caso contrario

Descripción

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. Si el archivo ya existe en el disco, la función no hace nada (no se lanza ningún error) y devuelve false.

Valor devuelto

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

Ejemplo

Creación de un archivo de preferencias en la carpeta principal:

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

.createAlias()

Historia
LanzamientoModificaciones
17 R5Añadidos

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

ParámetrosTipoDescripción
destinationFolder4D.Folder->Carpeta de destino para el alias o el acceso directo
aliasNameText->Nombre del alias o del atajo
aliasTypeInteger->Tipo de enlace del alias
Result4D.File<-Referencia del archivo del alias o de atajo

Descripción

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 defecto en macOS, la función crea un alias estándar. You can also create a symbolic link by using the aliasType parameter. Las siguientes constantes están disponibles:

ConstanteValorComentario
fk alias link0Enlace de alias (por defecto)
fk symbolic link1Enlace simbólico (sólo para macOS)

On Windows, a shortcut (.lnk file) is always created (the aliasType parameter is ignored).

Objeto devuelto

A 4D.File object with the isAlias property set to true.

Ejemplo

Quiere crear un alias para un archivo en su carpeta principal:

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

.creationDate

Historia
LanzamientoModificaciones
17 R5Añadidos

.creationDate : Date

Descripción

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

This property is read-only.

.creationTime

Historia
LanzamientoModificaciones
17 R5Añadidos

.creationTime : Time

Descripción

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()

Historia
LanzamientoModificaciones
17 R5Añadidos

.delete()

ParámetrosTipoDescripción
No requiere ningún parámetro

Descripción

The .delete() function deletes the file.

Si el archivo no existe en el disco, la función no hace nada (no se genera ningún error).

Si el archivo está abierto, el resultado depende del sistema operativo:

  • en Windows, se genera un error,
  • en macOS, no se genera ningún error y el archivo se elimina.
caution

.delete() can delete any file on a disk. Esto incluye los documentos creados con otras aplicaciones, así como las propias aplicaciones. .delete() should be used with extreme caution. Eliminar un archivo es una operación permanente y no se puede deshacer.

Ejemplo

Desea eliminar un archivo específico en la carpeta de la base de datos:

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

.exists

Historia
LanzamientoModificaciones
17 R5Añadidos

.exists : Boolean

Descripción

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

This property is read-only.

.extension

Historia
LanzamientoModificaciones
17 R5Añadidos

.extension : Text

Descripción

The .extension property returns the extension of the file name (if any). Una extensión siempre comienza por ".". La propiedad .extension devuelve la extensión del nombre del archivo (si lo hay).

This property is read-only.

.fullName

Historia
LanzamientoModificaciones
17 R5Añadidos

.fullName : Text

Descripción

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

This property is read-only.

.getAppInfo()

Historia
LanzamientoModificaciones
19Añadidos

.getAppInfo() : Object

ParámetrosTipoDescripción
ResultObject<-Contenido del archivo de recurso versión .exe/.dll o .plist

Descripción

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

La función debe utilizarse con un archivo .exe, .dll o .plist existente. Si el archivo no existe en el disco o no es un archivo .exe, .dll o .plist válido, la función devuelve un objeto vacío (no se genera ningún error).

La función sólo admite archivos .plist en formato xml (basados en texto). Se devuelve un error si se utiliza con un archivo .plist en formato binario.

Objeto devuelto con un archivo .exe o .dll

La lectura de un .exe o .dll sólo es posible en Windows.

Todos los valores de propiedades son de tipo Texto.

PropiedadTipo
InternalNameText
ProductNameText
CompanyNameText
LegalCopyrightText
ProductVersionText
FileDescriptionText
FileVersionText
OriginalFilenameText

Objeto devuelto con un archivo .plist

El contenido xml del archivo se analiza y las llaves se devuelven como propiedades del objeto, conservando sus tipos (texto, booleano, numérico). .plist dict is returned as a JSON object and .plist array is returned as a JSON array.

Ejemplo

 // mostrar información de copyright del archivo .exe de la aplicación (windows)
var $exeFile : 4D.File
var $info : Object
$exeFile:=File(Application file; fk platform path)
$info:=$exeFile.getAppInfo()
ALERT($info.LegalCopyright)

// mostrar información de copyright de un info.plist (cualquier plataforma)
var $infoPlistFile : 4D.File
var $info : Object
$infoPlistFile:=File("/RESOURCES/info.plist")
$info:=$infoPlistFile.getAppInfo()
ALERT($info.Copyright)

Ver también

.setAppInfo()

.getContent()

Historia
LanzamientoModificaciones
19 R2Devuelve 4D.Blob
17 R5Añadidos

.getContent( ) : 4D.Blob

ParámetrosTipoDescripción
Result4D.Blob<-Contenido del archivo

Descripción

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 devuelto

Un objeto 4D.Blob.

Ejemplo

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

 var $vPath : Text
$vPath:=Select document("";"*";"Select a document";0)
If(OK=1) //Si se ha seleccionado un documento
[aTable]aBlobField:=File($vPath;fk platform path).getContent()
End if

.getIcon()

Historia
LanzamientoModificaciones
17 R5Añadidos

.getIcon( { size : Integer } ) : Picture

ParámetrosTipoDescripción
sizeInteger->Longitud del lado de la imagen devuelta (píxeles)
ResultPicture<-Icono

Descripción

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 en realidad la longitud del lado del cuadrado que contiene el icono. Los iconos suelen definirse en 32x32 píxeles ("iconos grandes") o 16x16 píxeles ("iconos pequeños"). Si pasa 0 u omite este parámetro, se devuelve la versión "icono grande".

Si el archivo no existe en el disco, se devuelve un icono vacío por defecto.

Valor devuelto

File icon picture.

.getText()

Historia
LanzamientoModificaciones
17 R5Añadidos

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

ParámetrosTipoDescripción
charSetNameText->Nombre del juego de caracteres
charSetNumInteger->Número del conjunto de caracteres
breakModeInteger->Modo de tratamiento de los saltos de línea
ResultText<-Texto del documento

Descripción

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

Opcionalmente, puede designar el conjunto de caracteres que se utilizará para leer el contenido. Puede pasar:

  • 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. Las siguientes constantes del tema "Documentos del sistema" están disponibles:

ConstanteValorComentario
Document unchanged0Sin procesar
Document with native format1(Por defecto) Los saltos de línea se convierten al formato nativo del sistema operativo: CR (retorno de carro) en OS X, CRLF (retorno de carro + salto de línea) en Windows
Document with CRLF2Los saltos de línea se convierten al formato de Windows: CRLF (retorno de carro + salto de línea)
Document with CR3Los saltos de línea se convierten al formato OS X: CR (retorno de carro)
Document with LF4Los saltos de línea se convierten al formato Unix: LF (salto de línea)

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

Valor devuelto

Texto del archivo.

Ejemplo

Dado el siguiente documento de texto (los campos están separados por tabulaciones):

id name price vat
3 thé 1.06€ 19.6
2 café 1.05€ 19.6

Cuando se ejecuta este código:

 $myFile:=Folder(fk documents folder).file("Billing.txt") //UTF-8 por defecto
$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.

Aquí hay otro ejemplo con el mismo archivo, pero con un delimitador de línea 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

Historia
LanzamientoModificaciones
17 R5Añadidos

.hidden : Boolean

Descripción

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

Historia
LanzamientoModificaciones
17 R5Añadidos

.isAlias : Boolean

Descripción

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

Historia
LanzamientoModificaciones
17 R5Añadidos

.isFile : Boolean

Descripción

The .isFile property returns always true for a file.

This property is read-only.

.isFolder

Historia
LanzamientoModificaciones
17 R5Añadidos

.isFolder : Boolean

Descripción

The .isFolder property returns always false for a file.

This property is read-only.

.isWritable

Historia
LanzamientoModificaciones
17 R5Añadidos

.isWritable : Boolean

Descripción

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.

Ejemplo

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

.modificationDate

Historia
LanzamientoModificaciones
17 R5Añadidos

.modificationDate : Date

Descripción

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

This property is read-only.

.modificationTime

Historia
LanzamientoModificaciones
17 R5Añadidos

.modificationTime : Time

Descripción

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()

Historia
LanzamientoModificaciones
17 R5Añadidos

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

ParámetrosTipoDescripción
destinationFolder4D.Folder->Carpeta de destino
newNameText->Nombre completo del archivo trasladado
Result4D.File<-Archivo movido

Descripción

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 defecto, el archivo conserva su nombre cuando se mueve. If you want to rename the moved file, pass the new full name in the newName parameter. El nuevo nombre debe cumplir con las reglas de nomenclatura (por ejemplo, no debe contener caracteres como ":", "/", etc.), de lo contrario se devuelve un error.

Objeto devuelto

El objeto File movido.

Ejemplo

$DocFolder:=Folder(fk documents folder)
$myFile:=$DocFolder.file("Current/Infos.txt")
$myFile.moveTo($DocFolder.folder("Archives");"Infos_old.txt")

.name

Historia
LanzamientoModificaciones
17 R5Añadidos

.name : Text

Descripción

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

This property is read-only.

.open()

Historia
LanzamientoModificaciones
19 R7Añadidos

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

ParámetrosTipoDescripción
modeText->Modo de apertura: "read", "write", "append"
optionsObject->Opciones de apertura
Result4D.FileHandle<-Nuevo objeto File handle

Descripción

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:

modeDescripción
"read"(Por defecto) Crea un file handle para leer los valores en el archivo. Si el archivo no existe en el disco, se devuelve un error. Puede abrir tantos file handles como quiera en modo "read" en el mismo objeto File.
"write"Crea un file handle para escribir valores en el archivo (empezando por el inicio del contenido del archivo). Si el archivo no existe en el disco, se crea. Sólo se puede abrir un file handle en modo "write" en el mismo objeto File.
"append"Crea un file handle para escribir los valores en el archivo (empezando por el final del contenido del archivo). Si el archivo no existe en el disco, se crea. Sólo se puede abrir un file handle en modo "append" en el mismo 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):

opcionesTipoDescripciónPor defecto
.modeTextOpening mode (see mode above)"read"
.charsetTextConjunto de caracteres utilizado al leer o escribir en el archivo. Utilice el nombre estándar del conjunto (por ejemplo, "ISO-8859-1" o "UTF-8")"UTF-8"
.breakModeReadTexto o númeroModo de procesamiento de los saltos de línea utilizados al leer el archivo (ver abajo)"native" o 1
.breakModeWriteTexto o númeroModo de procesamiento de los saltos de línea utilizados al escribir en el archivo (ver abajo)"native" o 1

La función reemplaza todos los delimitadores originales de final de línea. Por defecto, se utiliza el delimitador nativo, pero puede definir otro delimitador. The .breakModeRead and .breakModeWrite indicate the processing to apply to end-of-line characters in the document. Puede utilizar uno de los siguientes valores (texto o número):

Modo de ruptura en textoBreak mode en numérico (constante)Descripción
"native"1 (Document with native format)(Por defecto) Los saltos de línea se convierten al formato nativo del sistema operativo: LF (salto de línea) en macOS, CRLF (retorno de carro + salto de línea) en Windows
"crlf"2 (Document with CRLF)Los fines de línea se convierten en CRLF (retorno de carro + salto de línea), el formato predeterminado de Windows
"cr"3 (Document with CR)Los fines de línea se convierten en CR (retorno de carro), el formato clásico por defecto de Mac OS
"lf"4 (Document with LF)Los fines de línea se convierten en LF (salto de línea), el formato Unix y macOS por defecto

The break mode as text value is case sensitive.

Ejemplo

Quiere crear un file handle para leer el archivo "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

Historia
LanzamientoModificaciones
17 R5Añadidos

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

Descripción

The .original property returns the target element for an alias, a shortcut, or a symbolic link file. El elemento objetivo puede ser:

  • un objeto File
  • un objeto de la carpeta

Para los archivos sin alias, la propiedad devuelve el mismo objeto File que el archivo.

This property is read-only.

.parent

Historia
LanzamientoModificaciones
17 R5Añadidos

.parent : 4D.Folder

Descripción

The .parent property returns the parent folder object of the file. Si la ruta representa una ruta del sitema (por ejemplo, "/DATA/"), se devuelve la ruta del sistema.

This property is read-only.

.path

Historia
LanzamientoModificaciones
17 R5Añadidos

.path : Text

Descripción

The .path property returns the POSIX path of the file. Si la ruta representa un filesystem (por ejemplo, "/DATA/"), se devuelve el filesystem.

This property is read-only.

.platformPath

Historia
LanzamientoModificaciones
17 R5Añadidos

.platformPath : Text

Descripción

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

This property is read-only.

.rename()

Historia
LanzamientoModificaciones
17 R5Añadidos

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

ParámetrosTipoDescripción
newNameText->Nuevo nombre completo del archivo
Result4D.File<-Archivo renombrado

Descripción

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. Si ya existe un archivo con el mismo nombre, se devuelve un error.

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.

Objeto devuelto

The renamed File object.

Ejemplo

Quiere renombrar "ReadMe.txt" como "ReadMe_new.txt":

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

.setAppInfo()

Historia
LanzamientoModificaciones
20Soporte de WinIcon
19Añadidos

.setAppInfo( info : Object )

ParámetrosTipoDescripción
infoObject->Propiedades a escribir en el archivo .plist o el recurso versión del archivo .exe/.dll

Descripción

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

La función debe utilizarse con un archivo .exe, .dll o .plist existente. Si el archivo no existe en el disco o no es un archivo .exe, .dll o .plist válido, la función no hace nada (no se genera ningún error).

La función sólo admite archivos .plist en formato xml (basados en texto). Se devuelve un error si se utiliza con un archivo .plist en formato binario.

info parameter object with a .exe or .dll file

Escribir la información de archivos .exe o .dll sólo es posible en Windows.

Each valid property set in the info object parameter is written in the version resource of the .exe or .dll file. Las propiedades disponibles son (toda otra propiedad será ignorada):

PropiedadTipoComentario
InternalNameText
ProductNameText
CompanyNameText
LegalCopyrightText
ProductVersionText
FileDescriptionText
FileVersionText
OriginalFilenameText
WinIconTextRuta Posix del archivo .ico. Esta propiedad sólo se aplica a los archivos ejecutables generados 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. Si pasa un valor de tipo diferente a texto, se convierte en una cadena.

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. Se aceptan todos los nombre de llaves. Los tipos de valores se conservan cuando es posible.

If a key set in the info parameter is already defined in the .plist file, its value is updated while keeping its original type. Las demás llaves existentes en el archivo .plist no se modifican.

Para definir un valor de tipo Fecha, el formato a utilizar es una cadena de timestamp json formada en ISO UTC sin milisegundos ("2003-02-01T01:02:03Z") como en el editor de plist Xcode.

Ejemplo

  // definir el copyright y versión de un archivo .exe (Windows)
var $exeFile; $iconFile : 4D.File
var $info : Object
$exeFile:=File(Application file; fk platform path)
$iconFile:=File("/RESOURCES/myApp.ico")
$info:=New object
$info.LegalCopyright:="Copyright 4D 2023"
$info.ProductVersion:="1.0.0"
$info.WinIcon:=$iconFile.path
$exeFile.setAppInfo($info)
  // definir algunas llaves en un archivo info.plist (todas las plataformas)
var $infoPlistFile : 4D.File
var $info : Object
$infoPlistFile:=File("/RESOURCES/info.plist")
$info:=New object
$info.Copyright:="Copyright 4D 2023" //text
$info.ProductVersion:=12 //integer
$info.ShipmentDate:="2023-04-22T06:00:00Z" //timestamp
$info.CFBundleIconFile:="myApp.icns" //for macOS
$infoPlistFile.setAppInfo($info)

Ver también

.getAppInfo()

.setContent()

Historia
LanzamientoModificaciones
17 R5Añadidos

.setContent ( content : Blob )

ParámetrosTipoDescripción
contentBLOB->Nuevos contenidos para el archivo

Descripción

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.

Ejemplo

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

.setText()

Historia
LanzamientoModificaciones
19 R3Por defecto para los nuevos proyectos: sin BOM y (macOS) LF para EOL
17 R5Añadidos

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

ParámetrosTipoDescripción
textText->Texto a almacenar en el archivo
charSetNameText->Nombre del juego de caracteres
charSetNumInteger->Número del conjunto de caracteres
breakModeInteger->Modo de tratamiento de los saltos de línea

Descripción

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. Cuando el archivo ya existe en el disco, se borra su contenido anterior, excepto si ya está abierto, en cuyo caso se bloquea su contenido y se genera un error.

In text, pass the text to write to the file. Puede ser un texto literal ("my text"), o un campo / variable texto 4D.

Opcionalmente, puede designar el conjunto de caracteres que se utilizará para la escritura del contenido. Puede pasar:

  • 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.

Si existe una marca de orden de bytes (BOM) para el conjunto de caracteres, 4D la inserta en el archivo a menos que el conjunto de caracteres utilizado contenga el sufijo "-no-bom" (por ejemplo, "UTF-8-no-bom"). Si no especifica un conjunto de caracteres, por defecto 4D utiliza el conjunto de caracteres "UTF-8" sin 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:

ConstanteValorComentario
Document unchanged0Sin procesar
Document with native format1(Por defecto) Los saltos de línea se convierten al formato nativo del sistema operativo: LF (salto de línea) en macOS, CRLF (salto de línea + retorno de carro) en Windows
Document with CRLF2Los fines de línea se convierten en CRLF (retorno de carro + salto de línea), el formato predeterminado de Windows
Document with CR3Los fines de línea se convierten en CR (retorno de carro), el formato clásico por defecto de Mac OS
Document with LF4Los fines de línea se convierten en LF (salto de línea), el formato Unix y macOS por defecto

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.

Ejemplo

$myFile:=File("C:\\Documents\\Hello.txt";fk platform path)
$myFile.setText("Hello world")

.size

Historia
LanzamientoModificaciones
17 R5Añadidos

.size : Real

Descripción

The .size property returns the size of the file expressed in bytes. Si el archivo no existe en el disco, el tamaño es 0.

This property is read-only.