File
Los objetos File
se crean con el comando File
. Contienen referencias a archivos de disco que pueden o no existir realmente en el disco. Por ejemplo, cuando se ejecuta el comando File
para crear un nuevo archivo, se crea un objeto File
válido, pero en realidad no se almacena nada en el disco hasta que se llama a la función file.create( )
.
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()
Objeto File
.copyTo( destinationFolder : 4D.Folder { ; newName : Text } { ; overwrite : Integer } ) : 4D.File copia el objeto |
.create() : Boolean creates a file on disk according to the properties of the |
.createAlias( destinationFolder : 4D.Folder ; aliasName : Text { ; aliasType : Integer } ) : 4D.File creates an alias (macOS) or a shortcut (Windows) |
.creationDate : Date la fecha de creación del archivo |
.creationTime : Time la hora de creación del archivo |
.delete( ) deletes the file |
.exists : Boolean true si el archivo existe en el disco |
.extension : Text la extensión del nombre del archivo (si lo hay) |
.fullName : Text el nombre completo del archivo, incluyendo su extensión (si la hay) |
.getAppInfo() : Object returns the contents of a .exe, .dll or .plist file information as an object |
.getContent( ) : 4D.Blob devuelve un objeto |
.getIcon( { size : Integer } ) : Picture el icono del archivo |
.getText( { charSetName : Text { ; breakMode : Integer } } ) : Text .getText( { charSetNum : Integer { ; breakMode : Integer } } ) : Text devuelve el contenido del archivo como texto |
.hidden : Boolean true si el archivo está configurado como "oculto" a nivel de sistema |
.isAlias : Boolean true si el archivo es un alias, un acceso directo o un enlace simbólico |
.isFile : Boolean siempre verdadero para un archivo |
.isFolder : Boolean siempre false para un archivo |
.isWritable : Boolean true si el archivo existe en el disco y es escribible |
.modificationDate : Date la fecha de la última modificación del archivo |
.modificationTime : Time la hora de la última modificación del archivo |
.moveTo( destinationFolder : 4D.Folder { ; newName : Text } ) : 4D.File moves or renames the |
.name : Text el nombre del archivo, sin extensión (si la hay) |
.original : 4D.File .original : 4D.Folder
|
.parent : 4D.Folder el objeto carpeta padre del archivo |
.path : Text la ruta POSIX del archivo |
.platformPath : Text la ruta del archivo expresada con la sintaxis de la plataforma actual |
.rename( newName : Text ) : 4D.File renames the file with the name you passed in newName and returns the renamed |
.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 el tamaño del archivo expresado en bytes |
File
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
File ( path : Text { ; pathType : Integer }{ ; * } ) : 4D.File
File ( fileConstant : Integer { ; * } ) : 4D.File
Parámetros | Tipo | Descripción | |
---|---|---|---|
path | Texto | -> | Ruta del archivo |
fileConstant | Integer | -> | Constante del archivo 4D |
pathType | Integer | -> | fk posix path (por defecto) o fk platform path |
* | -> | * para devolver el archivo de la base local | |
Resultado | 4D.File | <- | Nuevo objeto de archivo |
Descripción
El comando File
crea y devuelve un nuevo objeto de tipo 4D.File
. El comando acepta dos sintaxis:
File ( path { ; pathType } { ; * })
En el parámetro path, pase una ruta de archivo. Puede utilizar una cadena personalizada o un filesystem (por ejemplo, "/DATA/myfile.txt").
Sólo se admiten nombres de ruta absolutos con el comando
File
.
Por defecto, 4D espera una ruta expresada con la sintaxis POSIX. Si trabaja con los nombres de ruta de plataforma (Windows o macOS), debe declararlo utilizando el parámetro pathType. Las siguientes constantes están disponibles:
Constante | Valor | Comentario |
---|---|---|
fk platform path | 1 | Ruta expresada con una sintaxis específica de la plataforma (obligatoria en caso de nombre de ruta de plataforma) |
fk posix path | 0 | Ruta expresada con sintaxis POSIX (por defecto) |
File ( fileConstant { ; * } )
En el parámetro fileConstant, pase un archivo 4D interno o sistema, utilizando una de las siguientes constantes:
Constante | Valor | Comentario |
---|---|---|
Backup history file | 19 | Archivo 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 file | 13 | Archivo historial de copias de seguridad actual. Almacenado en la carpeta Logs de la aplicación. |
Backup settings file | 1 | Archivo backup.4DSettings por defecto (formato xml), almacenado en la carpeta Settings del proyecto |
Backup settings file for data | 17 | archivo backup.4DSettings del archivo de datos (formato xml), almacenado en la carpeta Settings de la carpeta data |
Build application log file | 14 | Archivo de historial actual en formato xml del generador de aplicaciones. Almacenado en la carpeta Logs. |
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. Almacenado en la carpeta Logs. |
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. Almacenado en la carpeta Logs. |
Diagnostic log file | 11 | Log file created by the SET DATABASE PARAMETER(Diagnostic log recording) command. Almacenado en la carpeta Logs. |
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. Almacenado en la carpeta Logs. |
HTTP log file | 8 | Log file created by the WEB SET OPTION(Web log recording) command. Almacenado en la carpeta Logs. |
IMAP Log file | 23 | Log file created by the SET DATABASE PARAMETER(IMAP Log) command. Almacenado en la carpeta Logs. |
Last backup file | 2 | Último archivo de copia de seguridad, llamado <applicationName>[bkpNum].4BK, almacenado en una ubicación personalizada. |
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). Almacenado en la carpeta Logs. |
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. Almacenado en la carpeta Logs. |
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). 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()
Histórico
Versión | Modificaciones |
---|---|
v18 R6 | Añadidos |
4D.File.new ( path : Text { ; pathType : Integer }{ ; * } ) : 4D.File
4D.File.new ( fileConstant : Integer { ; * } ) : 4D.File
Descripción
La función 4D.File.new()
crea y devuelve un nuevo objeto de tipo 4D.File
. Es idéntico al comando File
(acceso directo).
It is recommended to use the
File
shortcut command instead of4D.File.new()
.
.copyTo()
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.copyTo( destinationFolder : 4D.Folder { ; newName : Text } { ; overwrite : Integer } ) : 4D.File
Parámetros | Tipo | Descripción | |
---|---|---|---|
destinationFolder | 4D.Folder | -> | Carpeta de destino |
newName | Texto | -> | Nombre para la copia |
overwrite | Integer | -> | fk overwrite para sustituir los elementos existentes |
Resultado | 4D.File | <- | Archivo copiado |
Descripción
La función .copyTo()
copia el objeto File
en el destinationFolder especificado> .
La destinationFolder debe existir en el disco, de lo contrario se genera un error.
Por defecto, el archivo se copia con el nombre del archivo original. Si desea cambiar el nombre de la copia, pase el nuevo nombre en el parámetro newName. 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.
Si ya existe un archivo con el mismo nombre en la destinationFolder, por defecto 4D genera un error. Puede pasar la constante fk overwrite
en el parámetro overwrite para ignorar y sobrescribir el archivo existente
Constante | Valor | Comentario |
---|---|---|
fk overwrite | 4 | Sobrescribir los elementos existentes, si los hay |
Valor devuelto
El objeto File
copiado.
Ejemplo
Desea copiar un archivo imagen de la carpeta de documentos del usuario a la carpeta de la aplicación:
var $source; $copy : Object
$source:=Folder(fk documents folder).file("Pictures/photo.png")
$copy:=$source.copyTo(Folder("/PACKAGE");fk overwrite)
.create()
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
No disponible para archivos ZIP
.create() : Boolean
Parámetros | Tipo | Descripción | |
---|---|---|---|
Resultado | Booleano | <- | 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. If the file already exists on disk, the function does nothing (no error is thrown) and returns 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
Creation of a preferences file in the database folder:
var $created : Boolean
$created:=File("/PACKAGE/SpecialPrefs/"+Current user+".myPrefs").create()
.createAlias()
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.createAlias( destinationFolder : 4D.Folder ; aliasName : Text { ; aliasType : Integer } ) : 4D.File
Parámetros | Tipo | Descripción | |
---|---|---|---|
destinationFolder | 4D.Folder | -> | Carpeta de destino para el alias o el acceso directo |
aliasName | Texto | -> | Nombre del alias o del atajo |
aliasType | Integer | -> | Tipo de enlace del alias |
Resultado | 4D.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.
By default on macOS, the function creates a standard alias. You can also create a symbolic link by using the aliasType parameter. Las siguientes constantes están disponibles:
Constante | Valor | Comentario |
---|---|---|
fk alias link | 0 | Enlace de alias (por defecto) |
fk symbolic link | 1 | Enlace 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
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
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.creationDate : Date
Descripción
La propiedad .creationDate
devuelve la fecha de creación del archivo.
Esta propiedad es de sólo lectura.
.creationTime
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.creationTime : Time
Descripción
La propiedad .creationTime
devuelve la hora de creación del archivo (expresada como un número de segundos que comienza en 00:00).
Esta propiedad es de sólo lectura.
.delete()
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.delete( )
| Parámetros | Tipo | | Descripción | | ---------- | ---- | | ---------------------------- | | | | | No requiere ningún parámetro |
Descripción
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.
Ejemplo
You want to delete a specific file in the database folder:
$tempo:=File("/PACKAGE/SpecialPrefs/"+Current user+".prefs")
If($tempo.exists)
$tempo.delete()
ALERT("Archivo de preferencias del usuario borrado.")
End if
End if
.exists
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.exists : Boolean
Descripción
La propiedad .exists
devuelve true si el archivo existe en el disco, y false en caso contrario.
Esta propiedad es de sólo lectura.
.extension
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.extension : Text
Descripción
La propiedad .extension
devuelve la extensión del nombre del archivo (si lo hay). Una extensión siempre comienza por ".". La propiedad devuelve una cadena vacía si el nombre del archivo no tiene extensión.
Esta propiedad es de sólo lectura.
.fullName
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.fullName : Text
Descripción
La propiedad .fullName
devuelve el nombre completo del archivo, incluyendo su extensión (si la hay).
Esta propiedad es de sólo lectura.
.getAppInfo()
Histórico
Versión | Modificaciones |
---|---|
v19 | Añadidos |
.getAppInfo() : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
Resultado | Objeto | <- | Contents of .exe/.dll version resource or .plist file |
Descripción
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.
Todos los valores de propiedades son de tipo Texto.
Propiedad | Tipo |
---|---|
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.
Ejemplo
// 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)
Ver también
.getContent()
Histórico
Versión | Modificaciones |
---|---|
v19 R2 | Devuelve 4D.Blob |
v17 R5 | Añadidos |
.getContent( ) : 4D.Blob
Parámetros | Tipo | Descripción | |
---|---|---|---|
Resultado | 4D.Blob | <- | Contenido del archivo |
Descripción
La función .getContent()
devuelve un objeto 4D.Blob
que contiene todo el contenido de un archivo. Para obtener información sobre los BLOB, consulte la sección BLOB.
Valor devuelto
Un objeto 4D.Blob
.
Ejemplo
Para guardar el contenido de un documento en un campo BLOB
:
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()
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.getIcon( { size : Integer } ) : Picture
Parámetros | Tipo | Descripción | |
---|---|---|---|
size | Integer | -> | Longitud del lado de la imagen devuelta (píxeles) |
Resultado | Imagen | <- | Icono |
Descripción
La función .getIcon()
devuelve el icono del archivo.
El parámetro opcional size especifica las dimensiones en píxeles del icono devuelto. 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
Icono de archivo picture.
.getText()
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.getText( { charSetName : Text { ; breakMode : Integer } } ) : Text
.getText( { charSetNum : Integer { ; breakMode : Integer } } ) : Text
Parámetros | Tipo | Descripción | |
---|---|---|---|
charSetName | Texto | -> | Nombre del juego de caracteres |
charSetNum | Integer | -> | Número del conjunto de caracteres |
breakMode | Integer | -> | Modo de tratamiento de los saltos de línea |
Resultado | Texto | <- | Texto del documento |
Descripción
La función .getText()
devuelve el contenido del archivo como texto .
Opcionalmente, puede designar el conjunto de caracteres que se utilizará para leer el contenido. Puede pasar:
- en charSetName, una cadena que contiene el nombre del conjunto estándar (por ejemplo "ISO-8859-1" o "UTF-8"),
- o en charSetNum, el ID MIBEnum (número) del nombre del conjunto estándar.
Para conocer la lista de los conjuntos de caracteres que soporta 4D, consulte la descripción del comando
CONVERT FROM TEXT
.
Si el documento contiene una marca de orden de bytes (BOM), 4D utiliza el conjunto de caracteres que ha establecido en lugar del especificado en charSetName o charSetNum (este parámetro se ignora entonces). Si el documento no contiene una BOM y si charSetName o charSetNum se omite, por defecto 4D utiliza el conjunto de caracteres "UTF-8".
En breakMode, se puede pasar un número que indica el procesamiento a aplicar a los caracteres de fin de línea en el documento. Las siguientes constantes del tema "Documentos del sistema" están disponibles:
Constante | Valor | Comentario |
---|---|---|
Document unchanged | 0 | Sin procesar |
Document with native format | 1 | (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 CRLF | 2 | Los saltos de línea se convierten al formato de Windows: CRLF (retorno de carro + salto de línea) |
Document with CR | 3 | Los saltos de línea se convierten al formato OS X: CR (retorno de carro) |
Document with LF | 4 | Los saltos de línea se convierten al formato Unix: LF (salto de línea) |
Por defecto, cuando se omite el parámetro breakMode, los saltos de línea se procesan en modo nativo (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()
... obtiene para $txt
:
"id\tname\tprice\tvat\r\n3\tthé\t1.06€\t19.6\r\n2\tcafé\t1.05€\t19.6"
con \t
(tab) como separador y \r\n
(CRLF) como delimitador de línea.
Aquí hay otro ejemplo con el mismo archivo, pero con un delimitador de línea diferente:
$txt:=$myFile.getText("UTF-8", Document with LF)
En este caso, el contenido de $txt
es el siguiente:
"id\tname\tprice\tvat\n3\tthé\t1.06€\t19.6\n2\tcafé\t1.05€\t19.6"
Esta vez se utiliza \n
(LF) como delimitador de línea.
.hidden
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.hidden : Boolean
Descripción
La propiedad .hidden
devuelve true si el archivo está configurado como "oculto" a nivel de sistema, y false en caso contrario.
Esta propiedad es de sólo lectura.
.isAlias
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.isAlias : Boolean
Descripción
La propiedad .isAlias
devuelve true si el archivo es un alias, un acceso directo o un enlace simbólico, y false en caso contrario.
Esta propiedad es de sólo lectura.
.isFile
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.isFile : Boolean
Descripción
La propiedad .isFile
devuelve siempre verdadero para un archivo.
Esta propiedad es de sólo lectura.
.isFolder
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.isFolder : Boolean
Descripción
La propiedad .isFolder
devuelve siempre false para un archivo.
Esta propiedad es de sólo lectura.
.isWritable
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.isWritable : Boolean
Descripción
La propiedad .isWritable
devuelve true si el archivo existe en el disco y es escribible.
La propiedad verifica la capacidad de la aplicación 4D a escribir en el disco (derechos de acceso), no se basa únicamente en el atributo writable del archivo.
Esta propiedad es de sólo lectura.
Ejemplo
$myFile:=File("C:\\Documents\\Archives\\ReadMe.txt";fk platform path)
If($myFile.isWritable)
$myNewFile:=$myFile.setText("Added text")
End if
.modificationDate
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.modificationDate : Date
Descripción
La propiedad .modificationDate
devuelve la fecha de la última modificación del archivo.
Esta propiedad es de sólo lectura.
.modificationTime
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.modificationTime : Time
Descripción
La propiedad .modificationTime
devuelve la hora de la última modificación del archivo (expresada como un número de segundos que comienza en 00:00).
Esta propiedad es de sólo lectura.
.moveTo()
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.moveTo( destinationFolder : 4D.Folder { ; newName : Text } ) : 4D.File
Parámetros | Tipo | Descripción | |
---|---|---|---|
destinationFolder | 4D.Folder | -> | Carpeta de destino |
newName | Texto | -> | Nombre completo del archivo trasladado |
Resultado | 4D.File | <- | Archivo movido |
Descripción
The .moveTo()
function moves or renames the File
object into the specified destinationFolder.
La destinationFolder debe existir en el disco, de lo contrario se genera un error.
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. 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
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.name : Text
Descripción
La propiedad .name
devuelve el nombre del archivo, sin extensión (si la hay).
Esta propiedad es de sólo lectura.
.original
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.original : 4D.File
.original : 4D.Folder
Descripción
La propiedad .original
devuelveel elemento de destino para un alias, un acceso directo o un archivo de enlace simbólico. 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.
Esta propiedad es de sólo lectura.
.parent
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.parent : 4D.Folder
Descripción
La propiedad .parent
devuelve el objeto carpeta padre del archivo. Si la ruta representa una ruta del sistema (por ejemplo, "/DATA/"), se devuelve la ruta del sistema.
Esta propiedad es de sólo lectura.
.path
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.path : Text
Descripción
La propiedad .path
devuelve la ruta POSIX del archivo. Si la ruta representa un filesystem (por ejemplo, "/DATA/"), se devuelve el filesystem.
Esta propiedad es de sólo lectura.
.platformPath
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.platformPath : Text
Descripción
La propiedad .platformPath
devuelve la ruta del archivo expresada con la sintaxis de la plataforma actual.
Esta propiedad es de sólo lectura.
.rename()
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.rename( newName : Text ) : 4D.File
Parámetros | Tipo | Descripción | |
---|---|---|---|
newName | Texto | -> | Nuevo nombre completo para el archivo |
Resultado | 4D.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. 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.
Objeto devuelto
El objeto File
renombrado.
Ejemplo
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
Versión | Modificaciones |
---|---|
v19 | Añadidos |
.setAppInfo( info : Object )
Parámetros | Tipo | Descripción | |
---|---|---|---|
info | Objeto | -> | Properties to write in .exe/.dll version resource or .plist file |
Descripción
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):
Propiedad | Tipo |
---|---|
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. Se acepta todo nombre de llave. 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.
Ejemplo
// 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)
Ver también
.setContent()
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.setContent ( content : Blob )
Parámetros | Tipo | Descripción | |
---|---|---|---|
content | BLOB | -> | 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. Para obtener información sobre los BLOB, consulte la sección BLOB.
Ejemplo
$myFile:=Folder(fk documents folder).file("Archives/data.txt")
$myFile.setContent([aTable]aBlobField)
.setText()
Histórico
Versión | Modificaciones |
---|---|
v19 R3 | Default for new projects: no BOM and (macOS) LF for EOL |
v17 R5 | Añadidos |
.setText ( text : Text {; charSetName : Text { ; breakMode : Integer } } )
.setText ( text : Text {; charSetNum : Integer { ; breakMode : Integer } } )
Parámetros | Tipo | Descripción | |
---|---|---|---|
texto | Texto | -> | Texto a almacenar en el archivo |
charSetName | Texto | -> | Nombre del juego de caracteres |
charSetNum | Integer | -> | Número del conjunto de caracteres |
breakMode | Integer | -> | 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. 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. Puede pasar:
- en charSetName, una cadena que contiene el nombre del conjunto estándar (por ejemplo "ISO-8859-1" o "UTF-8"),
- o en charSetNum, el ID MIBEnum (número) del nombre del conjunto estándar.
Para conocer la lista de los conjuntos de caracteres que soporta 4D, consulte la descripción del comando
CONVERT FROM TEXT
.
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 | Valor | Comentario |
---|---|---|
Document unchanged | 0 | Sin procesar |
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 |
Document with CRLF | 2 | Line breaks are converted to CRLF (carriage return + line feed), the default Windows format |
Document with CR | 3 | Line breaks are converted to CR (carriage return), the default Classic Mac OS format |
Document with LF | 4 | Line breaks are converted to LF (line feed), the default Unix and macOS format |
Por defecto, cuando se omite el parámetro breakMode, los saltos de línea se procesan en modo nativo (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
Histórico
Versión | Modificaciones |
---|---|
v17 R5 | Añadidos |
.size : Real
Descripción
La propiedad .size
devuelve el tamaño del archivo expresado en bytes. Si el archivo no existe en el disco, el tamaño es 0.
Esta propiedad es de sólo lectura.