版本: RN: 0.64.0,react-native-fs: ^2.17.0
最新: RN: 0.64.1,react-native-fs: ^2.18.0,可用
持续中。。。
一、安装及配置
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')
MainApplication.java (注意:这里的代码,按照官网是缺后两个import的)
import com.rnfs.RNFSPackage;
import com.facebook.react.shell.MainReactPackage;
import java.util.Arrays;
public class MainApplication extends Application implements ReactApplication {
// ...
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(), // <---- add comma
new RNFSPackage() // <---------- add package
二、完整的创建,读取,删除,下载的案例:
import React, { Component } from 'react'
import { Button, View,ToastAndroid ,Image} from 'react-native'
import RNFS from 'react-native-fs'
export default class App extends Component {
state={sourceFile:'file:///'}
_create = () => {
RNFS.mkdir(RNFS.DocumentDirectoryPath+"/mydata") //新建目录
//新建文件,并写入内容
RNFS.writeFile(RNFS.DocumentDirectoryPath+"/test.txt", '一次学习,处处填坑', 'utf8')
.then(() => console.log(RNFS.DocumentDirectoryPath+"/test.txt 创建完成"))
_read = () => {
RNFS.readDir(RNFS.DocumentDirectoryPath)
.then((result) => {
result.forEach(file=>{
//读取常用文件特性
console.log(file.size,file.path,file.isFile())
//读取具体文件的内容
if(file.path.endsWith('.txt')){
RNFS.readFile(file.path,'utf8')
.then(content=>console.log(content))
_delete=()=>{
RNFS.unlink(RNFS.DocumentDirectoryPath+"/test.txt")
.then(()=>console.log('test.txt 已经被删除'))
_download=()=>{
let downloadUrl="http://johnyu.cn/cafe/ice.jpeg"
let target=RNFS.DocumentDirectoryPath+"/"+downloadUrl.split('/').slice(-1)//取出ice.jpeg
console.log(target)
let options={fromUrl:downloadUrl
,toFile:target
,begin:res=>{
ToastAndroid.show(`size:${res.contentLength},type:${res.headers["Content-Type"]}`,ToastAndroid.SHORT)
RNFS.downloadFile(options)
.promise
.then(res=>{
this.setState({sourceFile:'file://'+target})
render() {
return (
<Button onPress={this._create} title="创建文件及目录" />
<Button onPress={this._read} title="读目录及文件的演示" />
<Button onPress={this._delete} title="删除文件的演示" />
<Button onPress={this._download} title="下载文件的演示" />
<Image style={{width:200,height:200}} source={{uri:this.state.sourceFile}}/>
</View>