Specific difference between bufferedreader and filereader
In simple manner:
A FileReader class is a general tool to read in characters from a File. The BufferedReader class can wrap around Readers, like FileReader, to buffer the input and improve efficiency. So you wouldn't use one over the other, but both at the same time by passing the FileReader object to the BufferedReader constructor.
Very Detail
FileReader is used for input of character data from a disk file. The input file can be an ordinary ASCII, one byte per character text file. A Reader stream automatically translates the characters from the disk file format into the internal char format. The characters in the input file might be from other alphabets supported by the UTF format, in which case there will be up to three bytes per character. In this case, also, characters from the file are translated into char format.
As with output, it is good practice to use a buffer to improve efficiency. Use BufferedReader for this. This is the same class we've been using for keyboard input. These lines should look familiar:
BufferedReader stdin =
new BufferedReader(new InputStreamReader( System.in ));
These lines create a BufferedReader, but connect it to an input stream from the keyboard, not to a file.
Source: http://www.oopweb.com/Java/Documents/JavaNotes/Volume/chap84/ch84_3.html
Difference between buffered reader and file reader and scanner class
Well:
FileReader
is just aReader
which reads a file, using the platform-default encoding (urgh)BufferedReader
is a wrapper around anotherReader
, adding buffering and the ability to read a line at a timeScanner
reads from a variety of different sources, but is typically used for interactive input. Personally I find the API ofScanner
to be pretty painful and obscure.
To read a text file, I would suggest using a FileInputStream
wrapped in an InputStreamReader
(so you can specify the encoding) and then wrapped in a BufferedReader
for buffering and the ability to read a line at a time.
Alternatively, you could use a third-party library which makes it simpler, such as Guava:
File file = new File("foo.txt");
List<String> lines = Files.readLines(file, Charsets.UTF_8);
Or if you're using Java 7, it's already available for you in java.nio.file.Files
:
Path path = FileSystems.getDefault().getPath("foo.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
BufferedReader vs Scanner, and FileInputStream vs FileReader?
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();
}
What is the difference between Java's BufferedReader and InputStreamReader classes?
BufferedReader is a wrapper for both "InputStreamReader/FileReader", which buffers the information each time a native I/O is called.
You can imagine the efficiency difference with reading a character(or bytes) vis-a-vis reading a large no. of characters in one go(or bytes). With BufferedReader, if you wish to read single character, it will store the contents to fill its buffer (if it is empty) and for further requests, characters will directly be read from buffer, and hence achieves greater efficiency.
InputStreamReader converts byte streams to character streams. It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.
Hope it helps.
BufferedReader & FileReader read() Performance - Large Text File
Using BufferedReader
is indeed faster than using just FileReader.
I executed your code on my machine, with the following text file https://norvig.com/big.txt (6MB).
- The initial result shows roughly the same time. About 17 seconds each.
- However, this is because
System.out.print()
is a bottleneck (within the loop). Without print, the result is 4 times faster withBufferedReader
. 200ms vs 50ms. (Compare it to 17s before)
In other words, don't use System.out.print()
when benchmarking.
Example
An improved benchmark could look like this using StringBuilder
.
File file = new File("/Users/Desktop/shakes.txt");
FileReader reader = new FileReader(file);
int ch;
StringBuilder sb = new StringBuilder();
long start = System.currentTimeMillis();
while ((ch = reader.read()) != -1) {
//System.out.print((char) ch);
sb.append((char) ch);
}
long end = System.currentTimeMillis();
System.out.println(sb);
The above code provides the same output but performs much faster. It will accurately show the difference in speed when using a BufferedReader
.
Do I need to close() both FileReader and BufferedReader?
no.
BufferedReader.close()
closes the stream according to javadoc for BufferedReader and InputStreamReader
as well as
FileReader.close()
does.
Reading a .txt file using BufferedReader and FileReader
Answer might have already been given in another topic like: Read all lines with BufferedReader
So it might be a duplicate.
However when you read a file via BufferedReader it is recommended you do it like
FileReader filereader = new FileReader("data.txt");
BufferedReader ifile = new BufferedReader(filereader);
String N;
ArrayList<String> file_contents= new ArrayList<String>();
//List will now contain the whole txt
try {
while((N = input.readLine()) != null) {
file_contents.add(N);
}
ifile.close();
}
catch(IOException e){
e.printStackTrace();
}
And then break the list's contents to get what you want.
Using a try/catch block can avoid the error of not knowing how to handle that the file "data.txt" cannot be read.
Your way of doing it (while(true)) doesn't pass the name in any variable so it can be printed out and also just checks if the 1st line of your data.txt file is empty or not and does nothing with the remaining lines if that condition is true.
In addition to the above check if the source of your problem is in the txt file.
For example if its structure is the way you want it to be.
Related Topics
When to Use an Assertion and When to Use an Exception
Difference Between Openjdk and Adoptium/Adoptopenjdk
Display Numbers from 1 to 100 Without Loops or Conditions
Differencebetween Putting a Property on Application.Yml or Bootstrap.Yml in Spring Boot
JPA - Returning an Auto Generated Id After Persist()
Are There Any Java Method Ordering Conventions
How to Do Query Auto-Completion/Suggestions in Lucene
What Throws an Ioexception in Java
Installing Java on Os X 10.9 (Mavericks)
Using Eclipse Java Compiler (Ecj) in Maven Builds
The Most Sophisticated Way for Creating Comma-Separated Strings from a Collection/Array/List
Why Are Interface Method Invocations Slower Than Concrete Invocations
How to Determine If a Point Is Inside a 2D Convex Polygon
How to Prevent Eclipse from Hanging on Startup