FileUtils

The fileUtils context property provides file operations like reading, writing and listing files. More...

Import Statement: import
Since: V-Play 2.17.0

Properties

Methods

Detailed Description

This item is available as a context property from all QML components when V-Play is imported via import VPlay 2.0. It is accessible with the name fileUtils. It encapsulates methods that allow to read, write and list files.

This is an example to download a PDF file and then open it with the native PDF viewer application, using FileUtils::openFile(). It also uses the DownloadableResource type to download a pdf from a web location and store it on the device.

 import VPlayApps 1.0
 import QtQuick 2.0
 import VPlay 2.0

 App {
   id: app
   // uncomment this to remove the resources on startup, so you can test the downloading again
   //Component.onCompleted: pdfResource.remove()
   NavigationStack {
     Page {
       title: "Download PDF"

       Column {
         anchors.centerIn: parent

         AppButton {
           text: "Download / Open"
           onClicked: {
             if(pdfResource.available) openPdf()
             else pdfResource.download()
           }
         }
         AppText {
           text: "Status: " + pdfResource.status
         }
       }
     }
   }
   DownloadableResource {
     id: pdfResource
     source: "http://www.orimi.com/pdf-test.pdf"
     storageLocation: FileUtils.DocumentsLocation
     storageName: "pdf-test.pdf"
     extractAsPackage: false
     // if the download is competed, available will be set to true
     onAvailableChanged: if(available) openPdf()
   }
   function openPdf() {
     // you can also open files with nativeUtils.openUrl() now (for paths starting with "file://")
     //nativeUtils.openUrl(pdfResource.storagePath)
     fileUtils.openFile(pdfResource.storagePath)
   }
 }

Requirements for Reading Files on Android

To be able to read files with another app on Android, please make sure that the following 2 conditions are met:

  • You need to enable the paths you wish to use in android/res/xml/file_paths.xml. If this file does not exist yet, please create it. The default content is:
     <?xml version="1.0" encoding="utf-8"?>
     <paths>
     <files-path name="files" path="."/>
     <cache-path name="cache" path="."/>
     <external-path name="external" path="."/>
     </paths>
  • You need to specify a file provider in android/AndroidManifest.xml. You can add the following code just before the closing </application> tag (so it is a child of the <application>):
     <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true">
       <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"/>
     </provider>

Storage Location

The StorageLocation enumeration in FileUtils encapsulates the QStandardPaths for access in QML.

You can use these values with storageLocation() to obtain a writable path. DownloadableResource downloads and extracts files to these locations using its storageLocation property.

The following location types are supported:

Location Description
FileUtils.DesktopLocation Returns the user's desktop directory. This is a generic value on systems with no concept of a desktop.
FileUtils.DocumentsLocation Returns the directory containing user document files. This is a generic value. The returned path is never empty.
FileUtils.FontsLocation Returns the directory containing user's fonts. This is a generic value. Note that installing fonts may require additional, platform-specific operations.
FileUtils.ApplicationsLocation Returns the directory containing the user applications (either executables, application bundles, or shortcuts to them). This is a generic value. Note that installing applications may require additional, platform-specific operations. Files, folders or shortcuts in this directory are platform-specific.
FileUtils.MusicLocation Returns the directory containing the user's music or other audio files. This is a generic value. If no directory specific for music files exists, a sensible fallback for storing user documents is returned.
FileUtils.MoviesLocation Returns the directory containing the user's movies and videos. This is a generic value. If no directory specific for movie files exists, a sensible fallback for storing user documents is returned.
FileUtils.PicturesLocation Returns the directory containing the user's pictures or photos. This is a generic value. If no directory specific for picture files exists, a sensible fallback for storing user documents is returned.
FileUtils.TempLocation Returns a directory where temporary files can be stored. The returned value might be application-specific, shared among other applications for this user, or even system-wide. The returned path is never empty.
FileUtils.HomeLocation Returns the user's home directory (the same as QDir::homePath()). On Unix systems, this is equal to the HOME environment variable. This value might be generic or application-specific, but the returned path is never empty.
FileUtils.DataLocation Returns the same value as AppLocalDataLocation. This enumeration value is deprecated. Using AppDataLocation is preferable since on Windows, the roaming path is recommended.
FileUtils.CacheLocation Returns a directory location where user-specific non-essential (cached) data should be written. This is an application-specific directory. The returned path is never empty.
FileUtils.GenericDataLocation Returns a directory location where user-specific non-essential (cached) data, shared across applications, should be written. This is a generic value. Note that the returned path may be empty if the system has no concept of shared cache.
FileUtils.RuntimeLocation Returns a directory location where persistent data shared across applications can be stored. This is a generic value. The returned path is never empty.
FileUtils.ConfigLocation Returns a directory location where runtime communication files should be written, like Unix local sockets. This is a generic value. The returned path may be empty on some systems.
FileUtils.GenericConfigLocation Returns a directory location where user-specific configuration files should be written. This may be either a generic value or application-specific, and the returned path is never empty.
FileUtils.DownloadLocation Returns a directory for user's downloaded files. This is a generic value. If no directory specific for downloads exists, a sensible fallback for storing user documents is returned.
FileUtils.GenericCacheLocation Returns a directory location where user-specific configuration files shared between multiple applications should be written. This is a generic value and the returned path is never empty.
FileUtils.AppDataLocation Returns a directory location where persistent application data can be stored. This is an application-specific directory. To obtain a path to store data to be shared with other applications, use FileUtils.GenericDataLocation. The returned path is never empty. On the Windows operating system, this returns the roaming path.
FileUtils.AppLocalDataLocation Returns the local settings path on the Windows operating system. On all other platforms, it returns the same value as AppDataLocation.
FileUtils.AppConfigLocation Returns a directory location where user-specific configuration files should be written. This is an application-specific directory, and the returned path is never empty.

The resulting location depends on the underlying platform. Some might not be available on each platform. The function storageLocation() will then return an empty path.

Here are examples of the storage locations on each platform:

Location macOS Windows
FileUtils.DesktopLocation "~/Desktop" "C:/Users/<USER>/Desktop"
FileUtils.DocumentsLocation "~/Documents" "C:/Users/<USER>/Documents"
FileUtils.FontsLocation "/System/Library/Fonts" (not writable) "C:/Windows/Fonts" (not writable)
FileUtils.ApplicationsLocation "/Applications" (not writable) "C:/Users/<USER>/AppData/Roaming/Microsoft
/Windows/Start Menu/Programs"
FileUtils.MusicLocation "~/Music" "C:/Users/<USER>/Music"
FileUtils.MoviesLocation "~/Movies" "C:/Users/<USER>/Videos"
FileUtils.PicturesLocation "~/Pictures" "C:/Users/<USER>/Pictures"
FileUtils.TempLocation randomly generated by the OS "C:/Users/<USER>/AppData/Local/Temp"
FileUtils.HomeLocation "~" "C:/Users/<USER>"
FileUtils.DataLocation "~/Library/Application Support/<APPNAME>" "C:/ProgramData/<APPNAME>"
FileUtils.CacheLocation "~/Library/Caches/<APPNAME>" "C:/Users/<USER>/AppData/Local/<APPNAME>/cache"
FileUtils.GenericDataLocation "~/Library/Application Support" "C:/Users/<USER>/AppData/Local"
FileUtils.RuntimeLocation "~/Library/Application Support" "C:/Users/<USER>"
FileUtils.ConfigLocation "~/Library/Preferences" "C:/ProgramData/<APPNAME>"
FileUtils.GenericConfigLocation "~/Library/Preferences" "C:/Users/<USER>/AppData/Local"
FileUtils.DownloadLocation "~/Downloads" "C:/Users/<USER>/Downloads"
FileUtils.GenericCacheLocation "~/Library/Caches" "C:/Users/<USER>/AppData/Local/cache"
FileUtils.AppDataLocation "~/Library/Application Support/<APPNAME>" "C:/Users/<USER>/AppData/Roaming/<APPNAME>"
FileUtils.AppLocalDataLocation "~/Library/Application Support/<APPNAME>" "C:/Users/<USER>/AppData/Local/<APPNAME>"
FileUtils.AppConfigLocation "~/Library/Preferences/<APPNAME>" "C:/Users/<USER>/AppData/Local/<APPNAME>"
Location Linux
FileUtils.DesktopLocation "~/Desktop"
FileUtils.DocumentsLocation "~/Documents"
FileUtils.FontsLocation "~/.fonts"
FileUtils.ApplicationsLocation "~/.local/share/applications"
FileUtils.MusicLocation "~/Music"
FileUtils.MoviesLocation "~/Videos"
FileUtils.PicturesLocation "~/Pictures"
FileUtils.TempLocation "/tmp"
FileUtils.HomeLocation "~"
FileUtils.DataLocation "~/.local/share/<APPNAME>"
FileUtils.CacheLocation "~/.cache/<APPNAME>"
FileUtils.GenericDataLocation "~/.local/share"
FileUtils.RuntimeLocation "/run/user/<USER>"
FileUtils.ConfigLocation "~/.config"
FileUtils.GenericConfigLocation "~/.config"
FileUtils.DownloadLocation "~/Downloads"
FileUtils.GenericCacheLocation "~/.cache"
FileUtils.AppDataLocation "~/.local/share/<APPNAME>"
FileUtils.AppLocalDataLocation "~/.local/share/<APPNAME>"
FileUtils.AppConfigLocation "~/.config/<APPNAME>"
Location Android iOS
FileUtils.DesktopLocation "<APPROOT>/files" "<APPROOT>/Documents/Desktop"
FileUtils.DocumentsLocation "<USER>/Documents" "<APPROOT>/Documents"
FileUtils.FontsLocation "/system/fonts" (not writable) "<APPROOT>/Library/Fonts"
FileUtils.ApplicationsLocation not supported (directory not readable) not supported
FileUtils.ApplicationsLocation "<USER>/Music" "<APPROOT>/Documents/Music"
FileUtils.MoviesLocation "<USER>/Movies" "<APPROOT>/Documents/Movies"
FileUtils.PicturesLocation "<USER>/Pictures" "<APPROOT>/Documents/Pictures"
FileUtils.TempLocation "<APPROOT>/cache" "<APPROOT>/tmp"
FileUtils.HomeLocation "<APPROOT>/files" "<APPROOT>" (not writable)
FileUtils.DataLocation "<APPROOT>/files" "<APPROOT>/Library/Application Support"
FileUtils.CacheLocation "<APPROOT>/cache" "<APPROOT>/Library/Caches"
FileUtils.GenericDataLocation "<USER>" "<APPROOT>/Documents"
FileUtils.RuntimeLocation "<APPROOT>/cache" not supported
FileUtils.ConfigLocation "<APPROOT>/files/settings" "<APPROOT>/Library/Preferences"
FileUtils.GenericConfigLocation "<APPROOT>/files/settings" (there is no shared settings) "<APPROOT>/Library/Preferences"
FileUtils.DownloadLocation "<USER>/Downloads" "<APPROOT>/Documents/Downloads"
FileUtils.GenericCacheLocation "<APPROOT>/cache" (there is no shared cache) "<APPROOT>/Library/Caches"
FileUtils.AppDataLocation "<APPROOT>/files" "<APPROOT>/Library/Application Support"
FileUtils.AppLocalDataLocation "<APPROOT>/files/settings" "<APPROOT>/Library/Preferences/<APPNAME>"
FileUtils.AppConfigLocation "<APPROOT>/files" "<APPROOT>/Library/Application Support"

Multi-path URLs

FileUtils offers a function to find a file in multiple search locations. Use getMultiPathUrl() to retrieve a URL to a relative file path.

By default, this looks for files in the default location, which is the user's documents directory. Additional search paths can be added with addSearchPath. DownloadableResource automatically adds its storageLocation as search path, so files downloaded and extracted with it can be used right away with getMultiPathUrl().

Write, List, Read Files

The following example shows how to use writeFile() to write files to different folders. Afterwards the content is read and displayed with a Text element. Additionally, it lists the files of the Documents directory.

A JavaScript object is written to the file with JSON.stringify(). Afterwards it can be retrieved as object with JSON.parse().

  • A JavaScript object is converted to a JSON string with JSON.stringify().
  • A folder called Particles is created in the Documents directory.
  • A file called newParticle.json is created in this new folder. The JSON string is written to it.
  • A file called newConfig.json is created in the Documents directory. The JSON string is written to it.
  • Afterwards all .json files in the Documents directory and its subfolders are listed.
  • The newParticle.json file is read from the Particles folder in the Documents directory.
  • The original JavaScript object is parsed using JSON.parse().
 import VPlay 2.0
 import QtQuick 2.0

 GameWindow {

   Scene {
     id: scene

     Text {
       id: status
       anchors.fill: parent
       wrapMode: Text.WrapAtWordBoundaryOrAnywhere
       verticalAlignment: Text.AlignVCenter
       text: "Status:\n"
       color: "White"
     }

     Component.onCompleted: {
       var fileContentAsString = JSON.stringify({
                                                  data : "sampleData",
                                                  number: 7,
                                                  subArray: [1, 2, 3, 4],
                                                  subObject: { subData: "Hello world" }
                                                }, null, "  ")

       // write <Documents>/Particles/newParticle.json
       var fileName = fileUtils.storageLocation(FileUtils.DocumentsLocation, "Particles/newParticle.json")
       var success = fileUtils.writeFile(fileName, fileContentAsString)
       status.text += "Write Particles/newParticle.json success: " + success + "\n"

       if(!success)
         return

       // write <Documents>/newConfig.json
       fileName = fileUtils.storageLocation(FileUtils.DocumentsLocation, "newConfig.json")
       success = fileUtils.writeFile(fileName, fileContentAsString)
       status.text += "Write newConfig.json success: " + success + "\n"
       if(!success)
         return

       // list all .json files in <Documents>
       var dirName = fileUtils.storageLocation(FileUtils.DocumentsLocation)
       var stringList = fileUtils.listFiles(dirName, "*.json")

       var contentText = "\nFiles: \n"
       for(var i = 0; i < stringList.length; i++){
         contentText += stringList[i] + "\n"
       }

       // read <Documents>/Particles/newParticle.json
       fileName = fileUtils.storageLocation(FileUtils.DocumentsLocation, "Particles/newParticle.json")
       var data = fileUtils.readFile(fileName)
       contentText += "\nData:\n" + data

       status.text += contentText

       var jsonObj = JSON.parse(data)

       status.text += "\n\nRead property jsonObj.subObject.data:\n" +
           jsonObj.subObject.subData
     }
   }
 }

Property Documentation

[read-only] searchPaths : list<string>

This read-only property returns the current list of paths getMultiPathUrl() uses to find a URL. The order of this list determines the search order: the path with index 0 is searched first, then index 1 and so on.

To modify the searchPaths list property use the function addSearchPath().

By default, the searchPaths contains the Documents directory

See also addSearchPath(), removeSearchPath(), and getMultiPathUrl().


Method Documentation

url addSearchPath(string absoluteSearchPath, int searchPathIndex)

Adds absoluteSearchPath to the searchPaths list property. The absoluteSearchPath must start with a "/" on Linux-based platforms and with C:\ or another valid drive letter on Windows. To receive the absolute path to one of the supported StorageLocation directories, use storageLocation().

If no searchPathIndex is supplied, the absoluteSearchPath is appended to the end of the searchPaths property. This means it gets searched after all other searchPaths. You can define the order of the insertion by setting the searchPathIndex to anything between 0 and the size of the array.

See also getMultiPathUrl(), removeSearchPath(), and searchPaths.


bool copyFile(string source, string destination)

Copy a text file given by the source path to the destination path.

Both paths can either be absolute or relative to the DocumentsLocation.

This function is shorthand for reading the file's text contents with readFile() and then writing back with writeFile().

Note: The method does not use the platform's copy command because files can also be read from app assets (assets:/) and Qt resources (qrc:/).

See also readFile(), writeFile(), listFiles(), and removeDir().


string cropPathAndKeepFilename(string filePath, bool cropFileExtension)

Returns the file name of the file at filePath.

This removes the directory from the path and keeps just the file name. If the optional parameter cropFileExtension is true, the file's extension is also removed.

Example usage:

 //returns "file.txt"
 var fileName = fileUtils.cropPathAndKeepFilename("/path/to/file/file.txt")

 //returns "file"
 var fileNameWithoutExtension = fileUtils.cropPathAndKeepFilename("/path/to/file/file.txt", true)

See also stripSchemeFromUrl(), getUrlByAddingSchemeToFilename(), and getAbsolutePathFromUrlString().


string defaultWritablePath()

A default writable directory used for relative paths inside most FileUtils functions. This is the same as calling storageLocation(FileUtils.DocumentsLocation).

See also storageLocation().


string engineBasePath()

Returns the base path of the QML engine. This is the file path to the initial QML file that loads your app or game.

See also engineBaseUrlPath() and qmlEngineBaseUrlForObject().


string engineBaseUrlPath()

Returns the base path of the QML engine as a file://, assets:/ or qrc:/ URL. This is the file path to the initial QML file that loads your app or game.

See also engineBasePath().


bool existsFile(string filePath)

Returns true if the file at filePath exists.

Note: This checks for the file using findFileOrDirectoryIncludingResources. To only check for the absolute filePath itself, use existsFileWithoutAdoptions().

See also existsFileFromUrl(), existsFileWithoutAdoptions(), and findFileOrDirectoryIncludingResources().


bool existsFileFromUrl(url fileUrl)

Returns true if the file at fileUrl exists.

Allowed URLs are file://, asset:/ and qrc:/.

Note: This only checks for absolute file URLs. To check for relative paths as well, use existsFile().

See also existsFile().


bool existsFileWithoutAdoptions(string filePath)

Returns true if the file at filePath exists.

Note: This only checks for absolute file paths. To check for relative paths as well, use existsFile().

See also existsFile().


string findFileOrDirectoryIncludingResources(string filePath)

Returns the absolute path to a file at filePath, if it exists.

filePath can either be an absolute path, or a path relative to the engineBasePath(). This works for both loading QML files from the file system and from QRC resources.

The return value is an absolute path if any file could be found. Otherwise it is an empty string.


string getAbsolutePathFromUrlString(string filePath)

Returns the absolute path to the directory of the file at filePath.

This removes the protocol scheme and the file name.

See also stripSchemeFromUrl(), getUrlByAddingSchemeToFilename(), and cropPathAndKeepFilename().


string getBasePath(QtObject sourceObject)

Returns the base path of the given sourceObject as string.

You can pass a QML object and retrieve the folder its QML file is located in. This can be used with getPathUrl() to load files located in the same folder as other QML files.

See also getPathUrl().


url getMultiPathUrl(url fileUrl, QtObject contextObject)

Returns a valid URL to a file using the searchPaths. This method looks up the file represented by fileUrl in each search path, in order.

If fileUrl is an absolute URL, the method looks up this absolute path first. If this file does not exist, it searches for the file name of the URL in the searchPaths.

If it is a relative URL, it appends it to each search path to check if that file exists. You can supply a contextObject, it looks up this object's getBasePath() as absolute path before the searchPaths. You can also omit contextObject, in this case it uses the engineBasePath() as context path.

If it finds any file this way, it returns a valid absolute URL to this file. If it can't find any file, in neither of the searchPaths and also not in the absolute provided location, it returns an empty URL.

You can call this function with DownloadableResource, which automatically registers its storagePath as search path. Thus you can use downloaded and extracted files with getMultiPathUrl().

The following example looks for an image called "testImage.png" in the app directory, i.e. in the same folder as the qml file. If it does not exist there, it searches in the Documents directory and in all searchPaths.

 import QtQuick 2.0
 import VPlay 2.0

 GameWindow {

   Scene {
     id: scene

     Image {
       // if found in the folder of this qml file then use the image from the FileUtils.ApplicationsLocation
       // if not found in the ApplicationsLocation, search for it in the DocumentsLocation and then in the searchPaths
       source: fileUtils.getMultiPathUrl("testImage.png", scene)
     }

   }
 }

See also addSearchPath(), removeSearchPath(), and searchPaths.


url getPathUrl(string filePath, var source)

Returns the full URL to the path of source and the appended relative filePath.

source can either be a QML object or an absolute URL or file path. If source is an object, the path used is the absolute path to its QML file using getBasePath().

Following example displays an image located in the same folder as some other QML file:

 import QtQuick 2.0
 import VPlay 2.0

 import "subdirectory"

 GameWindow {

   Scene {
     id: scene

     // SomeObject.qml is located in another directory
     SomeObject {
       id: someObject
     }

     // someImage.png is in the same directory as SomeObject.qml
     Image {
       source: fileUtils.getPathUrl("someImage.png", someObject)
     }
   }
 }

If source is a URL or a string, the path used is source itself. You can retrieve absolute paths with storageLocation() or getMultiPathUrl().

When filePath is "first-image.png" and the source is "file://somePath/particles/second-image.png" it returns "file://somePath/particles/first-image.png".

Following example lists all files from the source folder of the initialValue (../assets/img/). Afterwards it adds the returned names to the source path of the initialValue. Now the file paths in the files array can be used by components in other QML files to load the images without using relative paths which would not work in other QML files.

 import QtQuick 2.0
 import VPlay 2.0

 GameWindow {

   Scene {
     id: scene

     property url initialValue: "../assets/img/stars.png"

     Component.onCompleted: {
       // list image files in the directory of the source image.
       var stringList = fileUtils.listFiles(initialValue, ["*.png"])
       // fire.png, water.png, ...

       // Create file list with all images
       var files = []
       for(var i = 0; i < stringList.length; i++){
         // get a path from the initialValue and adds the names of the image list
         // ../assets/img/fire.png, ../assets/img/water.png, ...
         var fileurl = fileUtils.getPathUrl(stringList[i], initialValue)
         files[i] = fileurl
       }
       console.debug(JSON.stringify(files))
     }
   }
 }

See also listFiles(), storageLocation(), getMultiPathUrl(), and getBasePath().


url getUrlByAddingSchemeToFilename(string filePath)

Returns the filePath as a file://, assets:/ or qrc:/ URL.

See also stripSchemeFromUrl(), stripSchemeFromUrl(), and cropPathAndKeepFilename().


list<string> listFiles(url path, list<string> nameFilter)

Lists and returns files from a path depending on the nameFilter containing an array of strings. If no name filter was used all files are listed in the defined location.

The path contains the relative or absolute path. If path is relative, the files are listed in the DocumentsLocation directory.

The name filter may define which files should be listed. Following example lists all files with .json and .txt file ending. The files are listed from the directory of the current QML file.

To list all files in the Documents directory, use a relative path.

 import QtQuick 2.0
 import VPlay 2.0

 GameWindow {
   id: window

   Scene {
     id: scene

     Component.onCompleted: {
       // this will return ["config.json"], as a config.json file is placed in the same directory as the main.qml file
       var stringList = fileUtils.listFiles(Qt.resolvedUrl("."), ["*.json", "*.txt"])
       console.log("All .json and .txt files in app:\n" + stringList.join(", "))

       // this will return all files in the FileUtils.DocumentsLocation
       stringList = fileUtils.listFiles(".", ["*.json", "*.txt"])
       console.log("All .json and .txt files in documents:\n" + stringList.join(", "))
     }
   }
 }

For a more detailed example read Write, List, Read Files.

See also readFile() and writeFile().


bool openFile(string fileName)

Opens the file or directory fileName with an external application. This is the same as calling NativeUtils::openUrl() with a file:// URL.

The parameter fileName can be an absolute or relative file or directory path. In this case it creates the URL by calling getUrlByAddingSchemeToFilename(). It can also be of url type with the file:// protocol.

If fileName points to a directory, it opens the directory in the default file browser. If fileName points to a file, it opens the file with the default app associated with the file type, if one exists.

Use this example code to open a file called pdf-test.pdf from the app assets with the default PDF viewer. The PDF file is located relative to the current QML file:

 import VPlayApps 1.0
 import VPlayPlugins 1.0
 import QtQuick 2.0

 App {
   id: app

   Component.onCompleted: {
     fileUtils.openFile(Qt.resolvedUrl("../assets/pdf-test.pdf"))
   }
 }

The following example uses DownloadableResource to download a PDF file to the user's documents directory. It then opens it with the default PDF viewer:

 import VPlayApps 1.0
 import QtQuick 2.0

 App {
   id: app

   DownloadableResource {
     source: "http://www.orimi.com/pdf-test.pdf"
     storageLocation: FileUtils.DocumentsLocation
     storageName: "pdf-test.pdf"
     extractAsPackage: false

     Component.onCompleted: {
       if(status === DownloadableResource.UnAvailable) {
         download()
       } else {
         openDownloadedFile()
       }
     }

     onStatusChanged: openDownloadedFile()

     function openDownloadedFile() {
       if(status === DownloadableResource.Available) {
         fileUtils.openFile(storagePath)
       }
     }
   }
 }

This method returns true if the file was opened successfully. It returns false if the platform cannot open this file type or directory.

Note: Depending on the platform, no file browser to open directories or app to open a specific file type may be installed. In this case, the call does nothing and returns false. Specifically, mobile platforms don't generally have file browsers for opening directories installed.

Note: To be able to open file:// URLs with another app on Android, if your targetSdkVersion in AndroidManifest.xml is 24 or higher, you need to enable the paths you wish to use in android/res/xml/file_paths.xml. Find detailed instructions here: Requirements for Reading Files on Android


string qmlEngineBaseUrlForObject(var object)

Returns the base path of the object's QML engine. This is the QML file path to the root of object's QML tree.

If object is in the same QML context as the current QML file, this is the same as engineBasePath().

See also engineBasePath().


string readFile(string fileName)

Reads a text file from fileName and returns the content of the file as string. If no file was found or an error occurred, an empty string is returned.

The fileName parameter contains the name with extension and its relative or absolute path. If file is relative, the file is read relative to the DocumentsLocation directory.

Following code reads a file from a subfolder in the application directory. It then reads a file from a subfolder of the Documents directory:

 import QtQuick 2.0
 import VPlay 2.0

 GameWindow {
   id: window

   Scene {
     id: scene

     // URL property is relative to this QML file
     property url configFile: "subfolder/file.json"

     Component.onCompleted: {
       var relativeData = fileUtils.readFile(configFile)
       // alternatively you can also call it directly, but you need Qt.resolvedUrl()
       // var data = fileUtils.readFile(Qt.resolvedUrl("subfolder/file.json"))
       console.log(relativeData)

       // this file name is relative to FileUtils.Documents
       var documentsData = fileUtils.readFile("subfolder/file.json")
       console.log(documentsData)
     }
   }
 }

The default path of the Documents directory depends on the target platform. See Storage Location for more information.

For a more detailed example see the section Write, List, Read Files.

See also writeFile(), copyFile(), listFiles(), and removeDir().


bool removeDir(string dirName)

Removes the directory at dirName recursively with all contained files and sub-directories.

dirName can be an absolute path or a path relative to DocumentsLocation.

Returns true if the directory was removed successfully or if it did not exist before calling the method. Returns false if an existing directory could not be removed.

See also readFile(), writeFile(), listFiles(), and copyFile().


url removeSearchPath(string absoluteSearchPath)

Removes the search path absoluteSearchPath from the searchPaths property. All occurrences of the path are removed.

See also getMultiPathUrl(), addSearchPath(), and searchPaths.


string storageLocation(enumeration location, string path)

Returns a writable file path for one of the StorageLocation enum constants using QStandardPaths::writableLocation(). The locations depend on the platform. Some might not be available on each platform. The function storageLocation() will then return an empty path.

The optional parameter path is a relative path appended to the storage location. You can also omit path, then the function returns the absolute path to the storage location itself.

For example, you can display an image stored in <Download directory>/_packages/myPackage/myImage.png:

 Image {
   source: fileUtils.storageLocation(FileUtils.DownloadLocation, "_packages/myPackage/myImage.png")
 }

This function ensures that the requested directory exists. If it does not exist it is created automatically. If the directory cannot be created, an empty string is returned.

See also defaultWritablePath().


string storageLocationDisplayName(enumeration location)

Returns a textual representation for one of the StorageLocation enum constants using QStandardPaths::displayName().


string stripSchemeFromUrl(var fileUrl)

Returns the fileUrl without the protocol scheme.

The parameter fileUrl can either be of string or URL type.

See also getUrlByAddingSchemeToFilename(), stripSchemeFromUrl(), and cropPathAndKeepFilename().


bool writeFile(string fileName, string stringData)

Writes stringData to a text file at fileName. Returns true if the file could be written or false otherwise.

The fileName contains the name with extension and its relative or absolute path. If fileName is relative, the file is written relative to the DocumentsLocation directory.

To write a file to one of the Storage Locations, use storageLocation() for the fileName.

Following code writes a file with a relative path to the Documents directory:

 var success = fileUtils.writeFile("TextFiles/myFile.txt", "test text")

Following code writes a file without a given sub-path directly to the Documents directory:

 var success = fileUtils.writeFile("myFile.txt", "test text")

Following code writes a file without a given sub-path to the Downloads directory:

 var fileName = fileUtils.storageLocation(FileUtils.DownloadLocation, "myFile.txt")
 var success = fileUtils.writeFile(fileName, "test text")

The default path of the Documents directory depends on the target platform. See Storage Location for more information.

For a more detailed example see the section Write, List, Read Files.

See also readFile(), copyFile(), listFiles(), and removeDir().


Voted #1 for:

  • Easiest to learn
  • Most time saving
  • Best support

Develop Cross-Platform Apps and Games 50% Faster!

  • Voted the best supported, most time-saving and easiest to learn cross-platform development tool
  • Based on the Qt framework, with native performance and appearance on all platforms including iOS and Android
  • Offers a variety of plugins to monetize, analyze and engage users
FREE!
create apps
create games
cross platform
native performance
3rd party services
game network
multiplayer
level editor
easiest to learn
biggest time saving
best support