-1

Hi I'm currently having issues with reading in a file in android studio. The file I want to read in is just a simple text file called test. This is the path of the file C:\Users\John\Documents\MadLibs\app\src\main\res\raw\test.txt. Here's what I'm trying:

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

I'm relitively new to android studio and really don't understand how to read in files. I assumed its just like java however everything I've tried fails. Anyone have any ideas?

John Lutz
  • 15
  • 5
  • 1
    This [link](https://stackoverflow.com/questions/12421814/how-can-i-read-a-text-file-in-android) might help you – ASN Mar 09 '18 at 01:19
  • 2
    Thanks I got something like this from that link: InputStream inputStream = this.getResources().openRawResource(R.raw.test); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); – John Lutz Mar 09 '18 at 01:30
  • Your phone can not read a file that is not in your sd card.You need to move the file from "C:" to your sdcard first. – Qian Sijianhao Mar 09 '18 at 08:52

2 Answers2

0

Reading a textfile in 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);
Manivash
  • 48
  • 6
0

To read a text file as a string, you can use the following method:

// @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;
}
ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96