Buffered Reader vs Scanner and FileInputStream vs FileReader?

Can someone explain to me why I can use FileInputStream or FileReader for BufferedReader? What's the difference? And at the same time, what is the advantage of the scanner over the BufferedReader. I read that it helps through tokenization, but what does it mean?

+5
source share
2 answers
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(); } 
+9
source

Dexter's answer is already helpful, but an additional explanation might be useful:

In the genetic: InputStream provides only access to byte data from the source. The reader can be wrapped around the stream and adds the correct encoding of the text, so now you can read the characters. BufferedReader can be wrapped around read operations with the buffer, so instead of 1 byte per call, it immediately reads the bunch, thereby reducing the number of system calls and improving performance in most cases.

For files:

FileInputStream is the easiest way to read data from files. If you do not want to process text encoding yourself, you can transfer it to InputStreamReader, which can be wrapped in BufferedReader. Alternatively, you can use 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, the scanner is very useful. But, as already mentioned, this will add some overhead to creating these expressions, so use it only when necessary.

+2
source

Source: https://habr.com/ru/post/1207761/


All Articles