在android studio中读取文本文件

时间:2018-03-09 01:07:21

标签: java android android-studio io

您好我目前在android studio中的文件中阅读时遇到问题。我想要读入的文件只是一个名为test的简单文本文件。这是文件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一样,但我尝试过的一切都失败了。有人有什么想法吗?

2 个答案:

答案 0 :(得分:0)

在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);

答案 1 :(得分:0)

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

// @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;
}