The FileFolder component provides access to directory structures and their contents. It doesn't include the features of Qt FileDialog. FileDialog should be used if its features are required. More...
Import Statement: | import ArcGIS.AppFramework 1.0 |
Inherits: |
Properties
- exists : bool
- folderName : string
- listSeparator : QChar
- path : string
- separator : QChar
- size : int
- url : url
Signals
- movedFileToTrash(string originalFile)
- movedFileToTrash(string originalFile, object pathInTrash)
- movedFileToTrash(string originalFile, object pathInTrash, string error)
Methods
- bool cd(string path)
- bool cdUp()
- bool copyFile(string fileName, string filePath)
- File file(string fileName)
- bool fileExists(string fileName)
- FileInfo fileInfo(string fileName)
- QStringList fileNames()
- QStringList fileNames(object nameFilter)
- QStringList fileNames(object nameFilter, bool subFolders)
- string filePath(string fileName)
- url fileUrl(string fileName)
- FileFolder folder(string folderName)
- QStringList folderNames()
- QStringList folderNames(object nameFilter)
- QStringList folderNames(object nameFilter, bool subFolders)
- string fromNativeSeparators(string pathName)
- bool makeFolder()
- bool makePath(string path)
- object moveFileToTrash(string fileName)
- moveFileToTrashAsync(string fileName)
- object readCsvFile(string fileName)
- object readCsvFile(string fileName, object options)
- object readFile(string fileName)
- object readFile(string fileName, object options)
- object readJsonFile(string fileName)
- string readTextFile(string fileName)
- object readXmlFile(string fileName)
- refresh()
- string relativeFilePath(string fileName)
- bool removeFile(string fileName)
- bool removeFolder(string folderName)
- bool removeFolder(string folderName, bool recursive)
- bool removeFolder()
- bool removePath(string path)
- bool renameFile(string oldFileName, string newFileName)
- Settings settingsFile(string fileName)
- string toNativeSeparators(string pathName)
- bool writeFile(string fileName, object content)
- bool writeFile(string fileName, object content, object options)
- bool writeJsonFile(string fileName, object json)
- bool writeTextFile(string fileName, string text)
Detailed Description
The FileFolder component is used to manipulate path names, access information regarding paths and files, and manipulate the underlying file system.
Following code snippet creates a sample 'city.json' file inside a new 'ArcGIS/Data/json' folder, reads it then deletes it.
FileFolder { id: fileFolder path: "~/ArcGIS/Data/json" function random_population(min_pop, max_pop) { return Math.round(min_pop + Math.random() * (max_pop - min_pop)); } Component.onCompleted: { console.log("fileFolder.path: %1".arg(JSON.stringify(fileFolder.path))); // qml: fileFolder.path: "C:/Users/step7069/ArcGIS/Data/json" console.log("fileFolder.url: %1".arg(JSON.stringify(fileFolder.url))); // qml: fileFolder.url: file:///C:/Users/step7069/ArcGIS/Data/json var ok = fileFolder.makeFolder(); console.log("fileFolder.makeFolder: %1".arg(JSON.stringify(ok))); // qml: fileFolder.makeFolder: true var files = fileFolder.fileNames("*.json"); console.log("fileFolder.fileNames: %1".arg(JSON.stringify(files))); // qml: fileFolder.fileNames: ["sample.json"] ok = fileFolder.writeJsonFile("city.json", { 'city': 'Redlands', country: 'USA', pop: random_population(70000, 80000) } ); console.log("writeJsonFile: %1".arg(JSON.stringify(ok))); // qml: writeJsonFile: true var text = fileFolder.readTextFile("city.json"); console.log("text: %1".arg(JSON.stringify(text))); // qml: text: "{\n \"city\": \"Redlands\",\n \"country\": \"USA\",\n \"pop\": 72239\n}\n" var json = fileFolder.readJsonFile("city.json"); console.log("json: %1".arg(JSON.stringify(json))); // qml: json: {"city":"Redlands","country":"USA","pop":72239} files = fileFolder.fileNames("*.json"); console.log("fileFolder.fileNames: %1".arg(JSON.stringify(files))); // qml: fileFolder.fileNames: ["city.json","sample.json"] ok = fileFolder.removeFile("city.json"); console.log("removeFile: %1".arg(JSON.stringify(ok))); // qml: removeFile: true files = fileFolder.fileNames("*.json"); console.log("fileFolder.fileNames: %1".arg(JSON.stringify(files))); // qml: fileFolder.fileNames: ["sample.json"] } }
Property Documentation
Returns true if the path you have set for the FileFolder component exists, returns false if it doesn't.
String value of the currently mapped folders name.
FileFolder { id: fileFolder path: AppFramework.userHomePath } Text { text: fileFolder.folderName }
Returns the native path list separator. This will be ':' under Unix systems, and ';' under Windows.
Shows the address of the FileFolder object e.g. "c:\temp
".
Returns the native directory separator. This will be "/" under Unix systems, and "\" under Windows.
You don't need to use this function to build file paths. If you always use "/", Qt will translate your paths to conform to the underlying operating system. If you want to display paths to the user using their operating system's separator use toNativeSeparators().
Example: file:///C:/Users/<username>/ArcGIS/AppStudio/Apps/5bcae37ffdaf4aeabdd4ded6b9ecdb6b
Signal Documentation
Note: The corresponding handler is onMovedFileToTrash
.
Note: The corresponding handler is onMovedFileToTrash
.
Method Documentation
Changes the directory
Returns true if the directory can be successfully changed to the directory string supplied. Returns false if the directory can't be changed to the location supplied.
Item { FileFolder { id: fileFolder path: AppFramework.userHomePath } Text { text: fileFolder.path anchors {left: button.right; margins: 5} } Button { id: button text: qsTr("Go to Documents folder...") onClicked: fileFolder.cd(fileFolder.path + "/Documents"); } }
The path parameter
The string of the directory that is going to be set. This can be a hard coded string such as "c:\temp
\data
" or could also be a variable that you create:
var myFolder = AppFramework.userHomePath + "/temp/data";
Changes directory by moving one directory up from the current directory.
As AppStudio is built for various platforms it is good practice to use relative paths that are standardized by the AppFramework and this method helps you traverse the directory structure.
Item { FileFolder { id: fileFolder path: AppFramework.userHomePath } Text { text: fileFolder.path anchors {left: button.right; margins: 5} } Button { id: button text: qsTr("Go up...") onClicked: canMoveUp = fileFolder.cdUp() enabled: canMoveUp } }
Copy the file.
This sample creates a button that copies a file.
Item { FileFolder { id: fileFolder path: AppFramework.userHomePath } Text { text: copied ? qsTr("File copied :)") : fileFolder.path anchors {left: button.right; margins: 5} } Button { id: button text: qsTr("Copy text files...") onClicked: copied = fileFolder.copyFile("Text.txt", fileFolder.path + "/Documents/Texts/Bruce.txt"); } }
The fileName parameter
The name of the file to be copied:
"YourFile.file"
The filePath parameter
Although a path, this property requires a filename as part of it. You could simply be copying a file in the app's default directory or use it to move the file to a different location:
copyFile("Text.txt", "Bruce.txt");
or
copyFile("Text.txt", fileFolder.path + "/Documents/Texts/Bruce.txt")
File file(string fileName) |
The fileName parameter
Checks whether the file exists
Returns true if the file named fileName exists. If file doesn't exist returns false.
var fileExists = fileFolder.fileExists("bruce.txt"); console.log(qsTr("The file exists?"), fileExists);
The fileName parameter
The name of the file to be checked:
"YourFile.file"
FileInfo fileInfo(string fileName) |
Creates a fileInfo
This method returns a JSON object for you to consume in your application.
Item { FileFolder { id: fileFolder path: AppFramework.userHomePath } Text { text: JSON.stringify(fileFolder.fileInfo("Text.txt", undefined, 2)) } }
The fileName parameter
The name of the file to be inspected:
"YourFile.file"
List all files in the current folder. Files in the subfolders are not included.
The method returns a string list of file names.
Item { FileFolder { id: fileFolder path: AppFramework.userHomePath + "/Pictures" onPathChanged: repeater.model = fileFolder.fileNames("*.jpg", false) } Column { anchors.fill: parent spacing: 3 Text { text: fileFolder.path font.pixelSize: 20 } Rectangle { border { color: "blue" width: 1 } width: parent.width height: 2 } Repeater { id: repeater delegate: Text { text: modelData } } } }
Filter files in the current folder using nameFilter. In this case, files in the subfolders are not included for filtering.
The following code snippet explains the usage of this method.
Item { FileDialog { id: fileDialog title: "Please choose a folder containing files to review" selectFolder: true onAccepted: { mediaFolder.url = folder var filesList = mediaFolder.fileNames("*.jpg") imageToReview.source = mediaFolder.fileUrl(filesList[0]) } } FileFolder { id: mediaFolder } Image { id: imageToReview anchors { left: parent.left top: toolbar.bottom right: parent.right bottom: parent.bottom } } }
The nameFilter parameter
List of files that can be used to filter the result.
"Bruce.txt" or "Bruce.*" or "*.txt" or "*.txt, *.jpg"
Filter files in the current folder using nameFilter. If sub folders set to true then the files in the sub folders are filtered as well. If sub folders set to false then the files in the sub folders are not filtered.
The nameFilter will be applied to both the file names and subfolder names. This means that if the name of the subfolder does not match the nameFilter, the files in the subfolder will not be filtered.
The nameFilter parameter
List of files that can be used to filter the result.
"Bruce.txt" or "Bruce.*" or "*.txt" or "*.txt, *.jpg"
The subFolders parameter
The boolean value determining whether or not subfolders will be filtered.
Removes all multiple directory separators "/" and resolves any "."s or ".."s found in the file path.
Where fileName can be a relative (to the current working folder) or absolute reference, filePath is an absolute reference.
The fileName parameter
Example: "./Images/redCircle.png"
Returns Url representation of fileName.
The following sample displays the Url filename within visual elements.
Item { FileFolder { id: fileFolder path: AppFramework.userHomePath + "/Pictures" onPathChanged: repeater.model = fileFolder.fileNames("*.jpg", true) } Column { anchors.fill: parent spacing: 3 Text { text: fileFolder.path font.pixelSize: 20 } Rectangle { border { color: "blue" width: 1 } width: parent.width height: 2 } Repeater { id: repeater delegate: Text { text: modelData MouseArea { anchors.fill: parent onClicked: { urlText.text = fileFolder.fileUrl(modelData) } } } } Rectangle { border { color: "blue" width: 1 } width: parent.width height: 2 } Text { id: urlText font.pixelSize: 16 } } }
The fileName parameter
Example: "./Bruce.txt"
FileFolder folder(string folderName) |
Creates a FileFolder object
This sample creates a button that makes a new file folder.
Item { FileFolder { id: fileFolder path: AppFramework.userHomePath } Button { id: button text: qsTr("Create folder") onClicked: { var newFileFolder = fileFolder.folder("Bruce"); folderMade = newFileFolder.makeFolder(); } } Text { anchors {left: button.right; margins: 5} text : folderMade ? qsTr("Created folder. Or it already exists") : "..." } }
The folderName parameter
String of a folder name. Example: "Bruce"
List directories within a FileFolders designated path. Directories in the subfolders are not included.
This sample displays all folders within the designated directory.
Item { FileFolder { id: fileFolder path: AppFramework.userHomePath onPathChanged: repeater.model = fileFolder.folderNames() } Column { anchors.fill: parent spacing: 3 Repeater { id: repeater delegate: Text { text: modelData } } } }
Option 2 of the folderNames method.
The folderNames methods provides optional inputs. The first is the nameFilter. This is a string that can help search for folders.
onPathChanged: repeater.model = fileFolder.folderNames("App*")
The nameFilter parameter
Examples: "Bruce" or "Br*" or "*r*"
Option 3 of folderNames method
Filter directories using nameFilter. If subFolders set to true then the directories in the subfolders are filtered as well. If subFolders set to false then the directories in the subfolders are not filtered.
The nameFilter will be applied to both the file names and subfolder names. This means that if the name of the subfolder does not match the nameFilter, the files in the subfolder will not be filtered.
onPathChanged: repeater.model = fileFolder.folderNames("Arc*", true)
The nameFilter parameter
Examples: "Bruce" or "Br*" or "*r*"
The subFolders parameter
true/false: Set to true to look in sub folders.
Returns the pathName parameter using '/' as file separator. For example, on Widnows, fromNativeSeparators("c:\winnt\system32") would return "c:/winnt/system32".
Be aware that on some platforms, the returned string will be the same as the parameter provided.
The pathName parameter
The file path name to convert the separators of.
Create folder.
If folder creation is successful returns true. If folder creation is unsuccessful returns false. If folder already exists returns true.
Item { FileFolder { id: fileFolder path: AppFramework.userHomePath } Button { id: button text: qsTr("Create folder") onClicked: { var newFileFolder = fileFolder.folder("Bruce"); folderMade = newFileFolder.makeFolder(); } } Text { anchors {left: button.right; margins: 5} text : folderMade ? qsTr("Created folder. Or it already exists") : "..." } }
Creates all parent directories necessary to create the directory.
Returns true if successful or if path already exists. If unsuccessful returns false.
In the following sample, when the button is clicked a new folder is created inside the mediaFolder:
Item { FileFolder { id: mediaFolder path: AppFramework.userHomePath } Button { anchors.centerIn: parent height: 30 width: 100 text: "click me" onClicked: mediaFolder.makePath("New Folder") } }
The path parameter
Examples: "./Bruce" or "c:/temp/Bruce"
Moves the file specified by the fileName parameter to the trash. On desktop platforms, this property returns the file's new filepath in the trash on success, or undefined on failure.
On Android and iOS, this method will return null regardless of if it was a success or failure.
The fileName parameter
The name of the file to move to the trash.
Moves the file specified by the fileName parameter to the trash. This method is asynchronous, and on completion emits the movedFileToTrash signal, with the original filename, its filepath in the trash location (for Windows and macOS), and any relevant error strings.
The fileName parameter
The name of the file to move to the trash.
Parses the given CSV file, presuming default values for all possible options.
The fileName parameter
The filename of the CSV to parse.
Parses the given CSV file, using all provided options. If an option is not set, this method will use its default.
Item { FileFolder { id: testFolder path: "./TestFolder/" } function runTest() { var options = {"delimiter": "|"} var inputFile = AppFramework.resolvedPath(testFolder.filePath("test.csv")); try { testFolder.readCsvFile(inputFile, options); } catch (error) { console.log("Error in " + error.fileName + ":" + error.lineNumber + ": " + error.message); } } Component.onCompleted: { runTest(); } }
The fileName parameter
The filename of the CSV file to parse.
The options parameter
A JSON object of options that alter the behavior of parsing the CSV file. The following parameters are supported, and when not set otherwise, use the default.
dataElementAsArray: Boolean. If set to true, the function will return a list of arrays. Otherwise, the function will return a list of objects. The default is false.
delimiter: String. Specifies the delimiter/value separator. This only works when a single character is provided. The default value is comma (,).
textQualifier: String. Specify the text qualifier/quote marks. Only works when a single character is provided. Default value is double quotation marks (").
trim: Boolean. Trim unquoted strings. Default value is true.
emptyValueAsNull: Boolean. Specify if an empty unquoted value should be interpreted as a null value, or an empty string. Note that any empty quoted value will always be treated as a string. Default value is true.
fields: Strings, separated by commas and enclosed in square brackets. Provide a list of custom headers. This only works with an array of strings, e.g. ["header1", "header2", "header3"]. If not specified, the method will use the first row in the file as the headers.
valueType: String. If set to "auto", unquoted field values read from the CSV will be automatically converted to the most compact numeric type and then fallback to a string format if more compact forms are not applicable. For example, if the value is not null, then the format will resort to int, then double, then string. If set to "text", this automatic conversion isn't performed, and the field values fall back to a string format. Default value is "auto"; if the value is set to anything other than "auto" or "text", it will also default to "auto".
locale: String | Locale. Specify the locale used when reading the file. Can be set using a localename string or a Qt.locale() object, for example "de_DE" or Qt.locale("de_DE"). By default, the "C" locale is used.
encoding: String. Specify the character encoding used to read the file if Byte Order Mark (BOM) is not detected. Default value is "UTF-8".
ignoreInvalidLines: Boolean. Specify if the function should ignore invalid lines in the CSV file. An invalid line is any row that includes a different number of fields to the header, a text qualifier or quote inside an unquoted field, an unescaped text qualifier or quote in a quoted field, or an end of file character inside a quoted field. Default value is true; if set to false, the function will always abort the execution and provide an error.
Reads data from the specified file
For example,
Item { FileFolder { id: fileFolder path: AppFramework.userHomePath Component.onCompleted: txt.text = readFile("Text.txt") } Text { id: txt anchors.fill: parent wrapMode: Text.WordWrap } }
The fileName parameter
Example: "Bruce.txt"
Optionally supply an set of options to help read the file.
For example,
Item { FileFolder { id: fileFolder path: AppFramework.userHomePath Component.onCompleted: txt.text = readFile("Text.txt", {"encode": "<encodingtype>"}) } Text { id: txt anchors.fill: parent wrapMode: Text.WordWrap } }
The fileName parameter
Example: "./Bruce.txt"
The options parameter
Encoding types are : � hex � base64
Returns a JSON object from a file that you can traverse and manipulate.
This sample reads the defined JSON file.
Item { FileFolder { id: fileFolder path: app.folder.path Component.onCompleted: { var jsonObject = readJsonFile("iteminfo.json"); Object.getOwnPropertyNames(jsonObject).forEach(function(val, idx, array) { txt.text += (val + ' -> ' + jsonObject[val] + "\n"); }); } } Text { id: txt anchors.fill: parent wrapMode: Text.WordWrap } }
The fileName parameter
Example: "Bruce.json"
Returns a string of the data in a text file.
This sample returns only a short section of a defined text file.
Item { FileFolder { id: fileFolder path: AppFramework.userHomePath Component.onCompleted: { var txtFile = readTextFile("Text.txt"); txt.text = txtFile + " (is " + txtFile.length + " characters long)"; } } Text{ id: txt anchors.fill: parent wrapMode: Text.WordWrap } }
The fileName parameter
Examples: "Bruce.txt" or "Bruce.json"
Returns an object containing the contents of an XML file.
The fileName parameter
The name of the .xml file to read from.
Refreshes content and information of the folder. Ideal for when other functions are changing the content.
Returns the path to fileName relative to the directory.
This sample returns to the path defined by the location of the given file.
Item { FileFolder { id: fileFolder path: AppFramework.userHomePath Component.onCompleted: { txt.text = relativeFilePath("c:/temp/Bruce.txt") } } Text { id: txt anchors.fill: parent wrapMode: Text.WordWrap } }
The fileName parameter
Example: "Bruce.txt" or "C:/temp/Bruce.txt" (Windows version)
Removes the file, fileName.
Returns true if the file is removed successfully. Returns false if the file is not removed successfully.
Item { FileFolder { id: fileFolder path: AppFramework.userHomePath Component.onCompleted: fileRemoved = removeFile("c:/temp/Bruce.txt") } Text{ id: txt text: fileRemoved ? "File was removed :)": "File not removed" anchors.fill: parent wrapMode: Text.WordWrap } }
The fileName parameter
Example: "Bruce.txt"
Option 2. Removes the directory specified by folderName only if it is empty.
If folder is removed successfully, returns true. If folder is not removed successfully, returns false. If folder does not exists returns true.
Item { FileFolder { id: fileFolder path: AppFramework.userHomePath Component.onCompleted: folderRemoved = removeFolder("c:/temp/NewFolder") } Text{ id: txt text: folderRemoved ? "Folder was removed :)": "Folder not removed" anchors.fill: parent wrapMode: Text.WordWrap } }
The folderName parameter
Examples: "Bruce" or "../Bruce" or "c:/temp/Bruce"
Removes the directory specified by folderName. If recursive is true removes the directory, including all its contents. If recursive is false removes the directory only if it is empty.
If folder is removed successfully, returns true. If folder is not removed successfully, returns false. If folder does not exists returns true.
Component.onCompleted: folderRemoved = removeFolder("c:/temp/NewFolder", false)
The folderName parameter
Examples: "Bruce" or "../Bruce" or "c:/temp/Bruce"
The recursive parameter
true/false. Default value is true.
Remove directory including all its contents. With no parameters, removes the directory regardless of contents.
If folder is removed successfully, returns true. If folder is not removed successfully, returns false. If the folder does not exist, returns true.
Removes all directories in path if they are empty.
This sample removes the directories within the folder, rather than the folder itself.
Item { FileFolder { id: fileFolder path: AppFramework.userHomePath Component.onCompleted: folderRemoved = removePath("Bruce") } Text { id: txt text: folderRemoved ? "Folder was removed :)": "Folder not removed" anchors.fill: parent wrapMode: Text.WordWrap } }
The path parameter
Examples: "./Bruce" or "c:/temp/Bruce"
Renames a file or directory from oldName to newName, and returns true if successful; otherwise returns false.
This method can be used when moving an file to a different location. Extending the example from makePath, the following would move the file "documentImage.jpg" into the sub folder called New Folder:
onClicked: mediaFolder.renameFile("documentImage.jpg", mediaFolder.path + "/New Folder/" + "documentImage.jpg")
The oldFileName parameter
Example: "documentImage.jpg"
The newFileName parameter
Example: "Bruce.jpg" or mediaFolder.path + "/New Folder/" + "documentImage.jpg"
Settings settingsFile(string fileName) |
Returns a settings object from a file that contains Settings information.
This sample displays a defined section of the settings file.
Item { FileFolder { id: fileFolder path: app.folder.path Component.onCompleted: { var appInfoSettings = settingsFile("appinfo.user"); txt.text = verboseKey + " setting: " + appInfoSettings.boolValue(verboseKey); } } Text{ id: txt anchors.fill: parent wrapMode: Text.WordWrap } }
The fileName parameter
For example, "appInfo.user"
Returns the pathName parameter, with '/' separators converted to separators appropriate for the underlying operating system. For example, on Windows, toNativeSeparators("c:/winnt/system32") would return "c:\winnt
\system32
".
Be aware that on some platforms, the returned string will be the same as the parameter provided.
The pathName parameter
The file path name to convert the native separators of.
Write data to a file.
This sample writes a text file using the designated content.
Item { FileFolder { id: fileFolder path: app.folder.path Component.onCompleted: { var content = "AppStudio Rocks!"; fileWritten = writeFile("MyFile.txt", content); } } Text { id: txt text: fileWritten ? "Written to file :)" : "Not Written" anchors.fill: parent wrapMode: Text.WordWrap } }
The fileName parameter
String value. Examples: "Bruce.txt" or "../Bruce.txt" or "c:/temp/Bruce.txt"
The content parameter
Examples: "Bruce" or {"name": "Bruce"} or [crack, a, tube, bruce]
Write data to a file, with additional options available for decoding.
This sample creates a text file with given content and further optional properties, in this case decoding.
Item { FileFolder { id: fileFolder path: app.folder.path Component.onCompleted: { var content ="41707053747564696f20526f636b7321" var actual = folder.writeFile("MyFile.txt", content, {"decode": "hex" }); } } Text { id: txt text: fileWritten ? "Written to file :)" : "Not Written" anchors.fill: parent wrapMode: Text.WordWrap } }
The fileName parameter
String value. Examples: "Bruce.txt" or "../Bruce.txt" or "c:/temp/Bruce.txt"
The content parameter
Examples: "Bruce" or {"name": "Bruce"} or [crack, a, tube, bruce]
The options parameter
Can accept the otpion to decode into one of two formats, hex or base64.
Write a JSON object to file.
This sample writes a file with the designated content and format into a JSON file.
Item { FileFolder { id: fileFolder path: app.folder.path Component.onCompleted: { var content = {"name" : "Bruce"} fileWritten = writeJsonFile("Bruce.json", content) } } Text { id: txt text: fileWritten ? "Written to file :)" : "Not Written" anchors.fill: parent wrapMode: Text.WordWrap } }
The fileName parameter
String value. Examples: "Bruce.json" or "../Bruce.json" or "c:/temp/Bruce.json"
The json parameter
Example:
{"name" : "Bruce"}
Creates a file with the filename and writes the text. If the file exists it will be overwritten.
This sample writes a file with the designated content into a text file.
Item { FileFolder { id: fileFolder path: app.folder.path Component.onCompleted: { var content = "AppStudio Rocks!" fileWritten = writeTextFile("Bruce.txt", content) } } Text { id: txt text: fileWritten ? "Written to file :)" : "Not Written" anchors.fill: parent wrapMode: Text.WordWrap } }
The fileName parameter
String value. Examples: "Bruce.txt" or "../Bruce.txt" or "c:/temp/Bruce.txt"
The text parameter
Example: "AppStudio Rocks!"