【问题标题】:How to create text file in React native (expo)?如何在 React native (expo) 中创建文本文件?
【发布时间】:2019-02-08 05:01:00
【问题描述】:

这是我正在尝试的功能。

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

但是有一个警告,有人知道怎么做吗?

-------------更新:console.log 输出-------------

[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: 代码更新---------------

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 似乎没有写入文件
------------更新-------------
我添加了一行,text.txt文件出现在我的android模拟器中的Document/DCIM/text.txt,但是必须使用“MediaLibrary.createAssetAsync”,如果是,如何控制文件夹名称?

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

【问题讨论】:

  • 您似乎将一个额外的参数“Hello World”传递给了只需要文件名参数的Expo.Filesystem.readAsStringAsync 方法。我怀疑它会将您的“Hello World”字符串视为options 对象,该对象定义应如何读取文件,如世博会文档中所述。
  • @iridescent 你是对的,但如何提醒字符串?它向我展示了 [object object]

标签: reactjs react-native expo


【解决方案1】:

我已经修改了问题中的代码,并最终设法完成了这项工作。此函数在 Downloads 文件夹中创建 .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)
    }
}

【讨论】:

  • 太长了,一旦创建了就没有办法找回来了?,我的意思是,保存在Download中的,获取后发送
  • 仅供参考:expo-permissions 现已弃用 — 该功能已移至其他直接使用这些权限的 expo 包(例如 expo-location、expo-camera)。该软件包将在即将发布的版本中删除。
猜你喜欢
  • 2020-10-20
  • 1970-01-01
  • 1970-01-01
  • 2015-12-31
  • 1970-01-01
  • 2022-01-07
  • 2022-01-20
  • 2022-01-20
  • 2018-04-18
相关资源
最近更新 更多