【问题标题】:Read text file from phone in android在android中从手机中读取文本文件
【发布时间】:2021-12-30 19:54:11
【问题描述】:

我正在尝试访问 android 中的文本文件,但它给出了错误 open failed: ENOENT (No such file or directory),因为文本文件存在于手机中。

        if (txt_file.endsWith(".txt")) {
              try {
                    Log.e("TAG", "path " + txt_file);
                    InputStream is = new FileInputStream(txt_file);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] b = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = is.read(b)) != -1) {
                         bos.write(b, 0, bytesRead);
                    }
                    byte[] bytes = bos.toByteArray();
                    byte[] dataToSave = Base64.encode(bytes, Base64.DEFAULT);

                    } catch (IOException e) {
                                e.printStackTrace();
                    }
          }

我在InputStream 之前记录了txt_file,它正在返回文本文件的正确路径。

【问题讨论】:

  • 尝试使用Scanner代替InputStream来读取文件
  • 您能否详细说明一下,因为is.read(b) 中存在错误,因为没有使用 Scanner 的读取方法。
  • Log.e("TAG", "path " + txt_file); 请告诉我们使用的路径。
  • 你应该添加:if ( !new File(txt_file).exists() return;
  • 您还应该添加:if ( !new File(txt_file).canRead() return;

标签: java android io text-files


【解决方案1】:

试试这个

 fun readFile(file: File?): String {
        var fileContent: String = ""
        try {
            val scan = Scanner(file)

            while (scan.hasNextLine()) {
                fileContent = scan.nextLine()
            }
            scan.close()
        } catch (e: IOException) {
            e.printStackTrace()
            fileContent = ""
        }
        return fileContent
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 2015-11-26
    相关资源
    最近更新 更多