HarmonyOS 鸿蒙Next 怎么能从picker选择的fileUri,使用readline?

HarmonyOS 鸿蒙Next 怎么能从picker选择的fileUri,使用readline?

怎么能从picker选择的fileUri,使用readline? 直接用fileUri、FileUri.path都说参数不对。

let file = fs.openSync(fileUri, fs.OpenMode.READ_ONLY)
let fileSize = fs.statSync(file.fd).size;
if (fileSize == 0) {
  return { error: ImportResultError.fileEmpty, total: 0, insert: 0 }
}
let result: ImportResult = { total: 0, insert: 0 };
let csvNameIndex: CsvNameIndex | undefined;
let charCount = 0;
let batchArray: LocationEntity[] = [];
let options: Options = {
  encoding: 'utf-8'
}; // let readIterator = fs.readLinesSync(fileUri, options); let readIterator = fs.readLinesSync(file.path, options); 

报错:

05-29 11:04:38.846 25129-25129 C04388/file_api com.xxx.xxx E [read_lines.cpp:192->Sync] Failed to read lines of the file, error: 2 05-29 11:04:38.846 25129-25129 C03f00/ArkCompiler com.xxx.xxx E [ecmascript] Pending exception before IsMixedDebugEnabled called in line:3200, exception details as follows: 05-29 11:04:38.846 25129-25129 C03f00/ArkCompiler com.xxx.xxx E Error: No such file or directory 05-29 11:04:38.846 25129-25129 C03f00/ArkCompiler com.xxx.xxx E at importCSVFile (app/src/main/ets/pages/inout/helper/ImportHelper.ets:44:28) 05-29 11:04:38.846 25129-25129 C03f00/ArkCompiler com.xxx.xxx E at anonymous (app/src/main/ets/pages/inout/InOutPage.ets:265:13)

更多关于HarmonyOS 鸿蒙Next 怎么能从picker选择的fileUri,使用readline?的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复
import fs, { Options } from '@ohos.file.fs';
import { common } from '@kit.AbilityKit';
import { picker } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  private appContext: common.Context = getContext(this);
  private fileDir: string = ''
  @State resultFileDir: string = ''
  createFile(){
    let cacheDir = this.appContext.cacheDir;
    this.fileDir = cacheDir + '/HelloWorldlee.txt'
    let file = fs.openSync(this.fileDir, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
    let writeLen = fs.writeSync(file.fd, '你好世界!');
    console.info("write data to file succeed and size is:" + writeLen);
    fs.closeSync(file)
  }
  async saveFile(){
    try {
      let documentSaveOptions = new picker.DocumentSaveOptions();
      documentSaveOptions.newFileNames = ['HelloWorld.txt'];
      let documentPicker = new picker.DocumentViewPicker();
      await documentPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
        let uri = documentSaveResult[0];
        this.resultFileDir = uri
        let sanFile = fs.openSync(this.fileDir, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
        let pubFile = fs.openSync(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
        fs.copyFileSync(sanFile.fd, pubFile.fd)
        fs.close(sanFile)
        fs.close(pubFile)
        console.info('DocumentViewPicker.save successfully, documentSaveResult uri: ' + JSON.stringify(documentSaveResult));
      }).catch((err: BusinessError) => {
        console.error('DocumentViewPicker.save failed with err: ' + JSON.stringify(err));
      });
      let pubFile = fs.openSync(this.resultFileDir, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
      let buf = new ArrayBuffer(4096);
      fs.readSync(pubFile.fd, buf);
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error('DocumentViewPicker failed with err: ' + JSON.stringify(err));
    }
  }
  build() {
    Row() {
      Column() {
        Button(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(()=>{
            this.createFile();
            this.saveFile();
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

更多关于HarmonyOS 鸿蒙Next 怎么能从picker选择的fileUri,使用readline?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙系统中,如果你已经通过picker组件选择了文件并获得了fileUri,要读取文件内容并使用readline(虽然HarmonyOS API没有直接提供readline方法,但你可以通过逐行读取文件内容来实现类似效果),你可以按照以下步骤操作:

  1. 获取文件路径:首先,使用UriFileProvider(或相应的内容解析器)将fileUri转换为实际文件路径。

  2. 打开文件:使用FileInputStreamFileReader打开文件。

  3. 逐行读取:利用BufferedReader包装FileReader,使用其readLine()方法逐行读取文件内容。

示例代码片段(注意需要根据实际环境调整异常处理和文件路径获取方式):

File file = new File(pathFromUri(fileUri));
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
    // 处理每一行内容
}
reader.close();

其中,pathFromUri方法需要你自己实现,用于将Uri转换为文件路径。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部