uni-app 文件读写操作

uni-app 文件读写操作

代码示例

getUriColumn(uri : Uri, selection : string, selectionArgs : string[]) {  
    const column : string = "_data";  
    const context = UTSAndroid.getAppContext() as Context;  
    const resolver = context.getContentResolver();  
    const cursor = resolver.query(uri, [column], selection, selectionArgs, "");  
    try {  
        if (cursor != null && cursor.moveToFirst()) {  
            const cursorIndex = cursor.getColumnIndexOrThrow(column);  
            const str = cursor.getString(cursorIndex);  
            console.log(str)  
        }  
    }  
    catch (e) {  

    }  
    finally {  
        if (cursor != null)  
            cursor.close()  
    }  
}

图片

Image 1

Image 2


更多关于uni-app 文件读写操作的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于uni-app 文件读写操作的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在uni-app中,文件读写操作通常依赖于uni.getFileSystemManager() API来获取文件系统管理器对象,进而进行文件的读取和写入操作。以下是一些示例代码,展示了如何在uni-app中进行基本的文件读写操作。

文件写入操作

// 获取文件系统管理器
const fs = uni.getFileSystemManager();

// 要写入的文件路径(这里以本地临时文件为例)
const filePath = `${wx.env.USER_DATA_PATH}/example.txt`;

// 要写入的内容
const data = 'Hello, uni-app!';

// 将数据写入文件
fs.writeFile({
  filePath: filePath,
  data: data,
  encoding: 'utf8',
  success: function () {
    console.log('文件写入成功');
  },
  fail: function (err) {
    console.error('文件写入失败', err);
  }
});

文件读取操作

// 获取文件系统管理器(同上)
const fs = uni.getFileSystemManager();

// 要读取的文件路径(与写入时的路径一致)
const filePath = `${wx.env.USER_DATA_PATH}/example.txt`;

// 读取文件内容
fs.readFile({
  filePath: filePath,
  encoding: 'utf8',
  success: function (res) {
    console.log('文件读取成功', res.data); // res.data为文件内容
  },
  fail: function (err) {
    console.error('文件读取失败', err);
  }
});

追加写入操作

如果需要向文件中追加内容,可以使用appendFile方法:

// 要追加的内容
const additionalData = '\nAppending some more text.';

// 将数据追加到文件
fs.appendFile({
  filePath: filePath,
  data: additionalData,
  encoding: 'utf8',
  success: function () {
    console.log('文件追加写入成功');
  },
  fail: function (err) {
    console.error('文件追加写入失败', err);
  }
});

注意事项

  1. 文件路径:在uni-app中,文件路径可以是相对路径或绝对路径。常用的路径常量包括wx.env.USER_DATA_PATH(用户文件目录)和wx.env.TEMP_FILE_PATH(临时文件目录)。

  2. 编码方式:读写文件时,需要指定编码方式(如utf8),以确保数据的正确读取和写入。

  3. 权限问题:在某些平台上,进行文件操作时可能需要申请相应的权限。确保在应用中正确处理权限请求。

通过上述代码示例,你可以在uni-app中实现基本的文件读写操作。根据具体需求,你可以进一步扩展这些功能,如处理二进制数据、文件删除、目录操作等。

回到顶部