Here is the function I'm trying.
saveFile = () => {
let filename = Expo.FileSystem.documentDirectory + "text.txt";
Expo.FileSystem.writeAsStringAsync(filename, "Hello World");
}
loadFile = () => {
let filename = Expo.FileSystem.documentDirectory + "text.txt";
let str = Expo.FileSystem.readAsStringAsync(filename, "Hello World");
//alert(str);
}
Warning:
[Unhandled promise rejection: Error: Argument of an incompatible class: class java.lang.String cannot be passed as an argument to parameter expecting interface java.util.Map.]
But there is a warning, anyone know how to do that?
-------------Update: console.log output--------------
[15:27:36] Promise {
[15:27:36] "_40": 0,
[15:27:36] "_55": null,
[15:27:36] "_65": 0,
[15:27:36] "_72": null,
[15:27:36] }
------------------update: code update---------------
saveFile = async () => {
let filename = Expo.FileSystem.documentDirectory + "text.txt";
await FileSystem.writeAsStringAsync(filename, "Hello World", { encoding: FileSystem.EncodingTypes.UTF8 });
}
loadFile = async () => {
let filename = Expo.FileSystem.documentDirectory + "text.txt";
file = await FileSystem.readAsStringAsync(filename, { encoding: FileSystem.EncodingTypes.UTF8 });
return file;
}
getTextFromFile = () => {
value = this.loadFile();
alert(value);
console.log(value);
}
the hello world seems didn't write into the file
------------update-------------
I added a line, the text.txt file is appeared at the Document/DCIM/text.txt in my android emulator, but is it a must to use "MediaLibrary.createAssetAsync", if yes, how to control the folder name?
await MediaLibrary.createAssetAsync(`${FileSystem.documentDirectory}text.txt`);
I've modified the code in the question and finally managed to make this work. This function creates .txt file in Downloads folder:
import * as MediaLibrary from 'expo-media-library';
import * as FileSystem from 'expo-file-system';
import * as Permissions from 'expo-permissions';
saveFile = async () => {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status === "granted") {
let fileUri = FileSystem.documentDirectory + "text.txt";
await FileSystem.writeAsStringAsync(fileUri, "Hello World", { encoding: FileSystem.EncodingType.UTF8 });
const asset = await MediaLibrary.createAssetAsync(fileUri)
await MediaLibrary.createAlbumAsync("Download", asset, false)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With