BufferedReader vs Scanner, and FileInputStream vs FileReader?

Dexter's answer is already useful, but some extra explanation might still help:

In genereal: An InputStream only provides access to byte data from a source. A Reader can be wrapped around a stream and adds proper text encoding, so you can now read chars. A BufferedReader can be wrapped around a Reader to buffer operations, so instead of 1 byte per call, it reads a bunch at once, thereby reducing system calls and improving performance in most cases.

For files:

A FileInputStream is the most basic way to read data from files. If you do not want to handle text encoding on your own, you can wrap it into a InputStreamReader, which can be wrapped into a BufferedReader. Alternatively, you can use a FilerReader, which should basically do the same thing as FileInputStream + InputStreamReader.

Now if you do not want to just read arbitrary text, but specific data types (int, long, double,...) or regular expressions, Scanner is quite useful. But as mentioned, it will add some overhead for building those expressions, so only use it when needed.


try {
    //Simple reading of bytes
    FileInputStream fileInputStream = new FileInputStream("path to file");
    byte[] arr = new byte[1024];
    int actualBytesRead = fileInputStream.read(arr, 0, arr.length);

    //Can read characters and lines now
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
    String lineRead = bufferedReader.readLine();
    char [] charArrr = new char[1024];
    int actulCharsRead = bufferedReader.read(charArrr, 0, charArrr.length);

    //File reader allows reading of characters from a file
    FileReader fileReader = new FileReader("path to file");
    actulCharsRead = fileReader.read(charArrr, 0, charArrr.length);

    //It is a good idea to wrap a bufferedReader around a fileReader
    BufferedReader betterFileReader = new BufferedReader(new FileReader(""));
    lineRead = betterFileReader.readLine();
    actulCharsRead = betterFileReader.read(charArrr, 0, charArrr.length);

    //allows reading int, long, short, byte, line etc. Scanner tends to be very slow
    Scanner scanner = new Scanner("path to file");
    //can also give inputStream as source
    scanner = new Scanner(System.in);
    long valueRead = scanner.nextLong();

    //might wanna check out javadoc for more info

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

Tags:

Java

Android