安裝react-native-fs npm npm install react-native-fs --save yarn yarn add react-native-fs 安卓配置 android/settings.gradle ... include ':react-native-fs' pro ...
安裝react-native-fs
npm
npm install react-native-fs --save
yarn
yarn add react-native-fs
安卓配置
android/settings.gradle
...
include ':react-native-fs'
project(':react-native-fs').projectDir = new File(settingsDir, '../node_modules/react-native-fs/android')
android/app/build.gradle
...
dependencies {
...
implementation project(':react-native-fs')
}
android\app\src\main\java\com\reactnative_demo\MainApplication.kt
把原代碼
import com.rnfs.RNFSPackage; // 導入模塊
// 下麵這段代碼要改
override fun getPackages(): List<ReactPackage> {
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
return PackageList(this).packages
}
改為
import com.rnfs.RNFSPackage; // 導入模塊
// 改成這樣
override fun getPackages(): List<ReactPackage> =
PackageList(this).packages.apply {
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
add(RNFSPackage()) // 如果報錯提示覆蓋註冊(已經自動註冊了),那麼把這行註釋掉即可
}
使用
import {StyleSheet, Text, View, Button} from 'react-native';
import React from 'react';
import RNFS from 'react-native-fs';
export default function CsvFile() {
const handleClick = () => {
const path = RNFS.ExternalStorageDirectoryPath + '/test.txt';
RNFS.writeFile(path, 'Lorem ipsum dolor sit amet', 'utf8')
.then(success => {
console.log('FILE WRITTEN! --> ', path);
})
.catch(err => {
console.log(err.message);
});
};
return (
<View>
<Button title="寫入文件" onPress={() => handleClick()} />
</View>
);
}
const styles = StyleSheet.create({});
關於存儲路徑
RNFS.MainBundlePath (String) 主包目錄的絕對路徑(在 Android 上不可用)
RNFS.CachesDirectoryPath (String) 緩存目錄的絕對路徑
RNFS.ExternalCachesDirectoryPath (String) 外部緩存目錄的絕對路徑(僅限安卓)
RNFS.DocumentDirectoryPath (String) 文檔目錄的絕對路徑
RNFS.DownloadDirectoryPath (String) 下載目錄的絕對路徑(僅在 android 上)
RNFS.TemporaryDirectoryPath (String) 臨時目錄的絕對路徑(在 Android 上回退到 Caching-Directory)
RNFS.LibraryDirectoryPath (String) NSLibraryDirectory 的絕對路徑(僅限 iOS)
RNFS.ExternalDirectoryPath (String) 外部文件的絕對路徑,共用目錄(僅限安卓)
RNFS.ExternalStorageDirectoryPath (String) 外部存儲的絕對路徑,共用目錄(僅限安卓)