如何在React Native(Expo)中创建文本文件?

10

这是我正在尝试的函数。

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);
}

警告:

[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.]

但需要注意的是,有人知道如何做吗?

-------------更新:控制台输出--------------

[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] }

------------------更新:代码更新---------------

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);
}

“Hello World”似乎没有被写入文件中。
------------ 更新 -------------
我添加了一行,文本.txt文件出现在我的Android模拟器的Document / DCIM / text.txt中,但是是否必须使用“MediaLibrary.createAssetAsync”,如果是,如何控制文件夹名称?

await MediaLibrary.createAssetAsync(`${FileSystem.documentDirectory}text.txt`);

看起来你正在向 Expo.Filesystem.readAsStringAsync 方法传递一个额外的参数 "Hello World",而该方法只需要文件名参数。我怀疑它将你的 "Hello World" 字符串视为一个 options 对象,定义了文件应该如何读取,正如 Expo 文档中所述。 - iridescent
@iridescent 你说得对,但是如何警告字符串呢?它显示给我 [object object]。 - hkguile
1个回答

8
我修改了问题中的代码,最终设法使其工作。这个函数在下载文件夹中创建 .txt 文件:
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)
    }
}

1
这已经太久了,但一旦创建了它,就没有办法把它拿回来了吗?我的意思是,如果保存在下载文件夹中,可以获取并发送它。 - plus
FYI:expo-permissions现已弃用 - 功能已移至其他直接使用这些权限的expo包(例如expo-location,expo-camera)。该软件包将在即将发布的版本中删除。 - ikiK
1
当使用 fileUri 时,我收到一个错误,指出它不是 SAF URI。 - Lego

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接