【问题标题】:Reading a textfile in android studio在 android studio 中读取文本文件
【发布时间】:2018-08-17 12:17:04
【问题描述】:

您好,我目前在 android studio 中读取文件时遇到问题。我要读入的文件只是一个简单的文本文件,名为 test.txt。这是文件 C:\Users\John\Documents\MadLibs\app\src\main\res\raw\test.txt 的路径。这是我正在尝试的:

BufferedReader br = new BufferedReader(new FileReader(getResources().openRawResourceFd(R.raw.test)));

我是 android studio 的新手,真的不明白如何读入文件。我认为它就像 java 但是我尝试过的一切都失败了。有人有什么想法吗?

【问题讨论】:

  • 这个link 可能对你有帮助
  • 谢谢我从那个链接得到了类似的东西: InputStream inputStream = this.getResources().openRawResource(R.raw.test); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
  • 您的手机无法读取SD卡中没有的文件。您需要先将文件从“C:”移动到您的SD卡中。

标签: java android android-studio io


【解决方案1】:

在 android studio 中读取文本文件

        FileInputStream fileInputStream=openFileInput("file.txt");
        InputStreamReader InputRead= new InputStreamReader(fileInputStream);

        char[] inputBuffer= new char[READ_BLOCK_SIZE];
        String s="";
        int charRead;

        while ((charRead=InputRead.read(inputBuffer))>0) {
            String rs=String.copyValueOf(inputBuffer,0,charRead);
            s +=rs;
        }
        InputRead.close();
        Log.d(TAG,s);

【讨论】:

    【解决方案2】:

    要将文本文件作为字符串读取,可以使用以下方法:

    // @RawRes will gives you warning if rawId is not from correct id for raw file.
    private String readRawFile(@RawRes int rawId) {
      String line;
      try {
        InputStream is = getResources().openRawResource(rawId);
    
        // read the file as UTF-8 text.
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        // Or using the following if API >= 19
        //BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
    
        StringBuilder result = new StringBuilder();
        while ((line = reader.readLine()) != null) {
          result.append(line);
        }
        reader.close();
        inputStream.close();
        line = result.toString();
      } catch (IOException e) {
        line = null;
      }
      return line;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多