0

Java code:

for (int i=0; i<13000; i++){
    new FileReader("helloWorld.txt");
}

gives:

> Exception in thread "main" java.io.FileNotFoundException: helloWorld.txt (Too many open files)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:112)
at java.base/java.io.FileReader.<init>(FileReader.java:60)
at Main.main(Main.java:14)

And it is pretty ok as there is not enough system resources. But I have no idea why this works:

for (int i=0; i<13000; i++){
    new BufferedReader(new FileReader("helloWorld.txt"));
}

As even there are many differences between FileReader and BufferedReader, there is still: new FileReader("helloWorld.txt") - so shouldnt it get out of resources as in 1st case?

Marcin Borowski
  • 163
  • 1
  • 1
  • 5
  • why in for loop `new FileReader("helloWorld.txt");` – Ryuzaki L Mar 09 '19 at 19:52
  • Well, to put it simply, a [`FileReader`](https://docs.oracle.com/javase/8/docs/api/java/io/FileReader.html) reads the entire file and a [`BufferedReader`](https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html) "buffers" the input. It helps to read the Java API documentation :) You can also check out this [question](https://stackoverflow.com/questions/9648811/specific-difference-between-bufferedreader-and-filereader) for more info. – Zephyr Mar 09 '19 at 19:59
  • What OS / JRE are you using? I can not reproduce this on Ubuntu 18.04 with Java 8.0.202. Tried 100_000 reads with FileReader() with no problem. – isapir Mar 09 '19 at 20:07
  • You are creating more garbage, specifically an 8K byte array, per file, so GC kicks in, and finalization closes the file. – user207421 Mar 09 '19 at 21:05

0 Answers0