You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/file-system-access/file-object.md
+79Lines changed: 79 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -955,3 +955,82 @@ Writes the specified text to the file at the current position, and appends a Lin
955
955
#### Returns
956
956
957
957
Boolean. `true` on success.
958
+
959
+
---
960
+
961
+
## File Object Examples
962
+
963
+
### Read & Write Files
964
+
965
+
The below example writes text to a file, then reads the contents of that file and presents it as an alert.
966
+
967
+
Keep in mind that this is just one way to do this. Some host apps may also require a user-specified permissions check before being able to access the local file system.
968
+
969
+
Note that this stores (and fetches) the file from the user's appdata folder, using the built-in [Folder.userData](../file-system-access/folder-object.md#folderuserdata) shortcut.
970
+
971
+
```js
972
+
/**
973
+
* Reads data from a given file in userdata folder
974
+
*
975
+
* @param{string}filename Filename, with extension
976
+
* @return{string} File contents, if file exists
977
+
*/
978
+
functionreadUserDataFromFile(filename) {
979
+
var userDataFolder =Folder.userData;
980
+
981
+
var filepath =userDataFolder.fullName+"/"+ filename;
982
+
var file =newFile(filepath);
983
+
984
+
// Default encoding
985
+
file.encoding="UTF-8";
986
+
987
+
if (!file.exists) {
988
+
throw"Could not find file '"+String(file.fsName);
989
+
}
990
+
991
+
file.open();
992
+
var contents =file.read();
993
+
file.close();
994
+
995
+
return contents;
996
+
}
997
+
998
+
/**
999
+
* Writes data to a given file in userdata folder
1000
+
*
1001
+
* @param{string}filename Filename, with extension
1002
+
* @param{string}data Data to write
1003
+
*/
1004
+
functionwriteUserDataToFile(filename, data) {
1005
+
var userDataFolder =Folder.userData;
1006
+
1007
+
var filepath =userDataFolder.fullName+"/"+ filename;
1008
+
var file =newFile(filepath);
1009
+
1010
+
// Default encoding
1011
+
file.encoding="UTF-8";
1012
+
1013
+
// Write file contents
1014
+
file.open("w");
1015
+
var success =file.write(data);
1016
+
file.close();
1017
+
1018
+
if (!success) {
1019
+
throw"Could not write to file '"+String(file.fsName);
0 commit comments