Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create text file in React native (expo)?

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`);
like image 792
hkguile Avatar asked Oct 16 '22 07:10

hkguile


1 Answers

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)
    }
}
like image 150
anro Avatar answered Nov 01 '22 09:11

anro