import React, { useEffect } from 'react';
import { View, Text, Button } from 'react-native';
import RNFS from 'react-native-fs';

const FileReadWriteExample = () => {
  // 定义文件路径
  const filePath = RNFS.DocumentDirectoryPath + '/example.txt';

  // 写入文件的函数
  const writeToFile = async () => {
    try {
      const content = 'Hello, this is a test file content.';
      // 使用 RNFS.writeFile 方法写入文件
      await RNFS.writeFile(filePath, content, 'utf8');
      console.log('File written successfully');
    } catch (error) {
      console.error('Error writing file:', error);
    }
  };

  // 读取文件的函数
  const readFromFile = async () => {
    try {
      // 使用 RNFS.readFile 方法读取文件
      const contents = await RNFS.readFile(filePath, 'utf8');
      console.log('File content:', contents);
    } catch (error) {
      console.error('Error reading file:', error);
    }
  };

  useEffect(() => {
    // 在组件挂载时创建文件目录
    RNFS.mkdir(RNFS.DocumentDirectoryPath)
      .then(() => {
        console.log('Directory created successfully');
      })
      .catch((error) => {
        console.error('Error creating directory:', error);
      });
  }, []);

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Button title="Write to File" onPress={writeToFile} />
      <Button title="Read from File" onPress={readFromFile} />
    </View>
  );
};

export default FileReadWriteExample;