I can not force BufferedReader to read the entire set of files. Is there a similar way to display the contents of files?

import java.io.BufferedReader; import java.io.File; import java.io.IOException; public class DirectoryShow { public static void main(String[] args) throws IOException { File f = new File("D:\\Files"); // current directory File[] files = f.listFiles(); for (File file : files) { BufferedReader br = new BufferedReader("D:\\Files"); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } System.out.print(" file:"); System.out.println(file.getCanonicalPath()); } } } 
  • one
    It is necessary to close BufferedReader - Barmaley
  • one
    What mean can not? What exactly is going on (error or something else)? Pay attention to the comment @Barmaley. - a_gura
  • > BufferedReader br = new BufferedReader("D:\\Files"); Did you mean new BufferedReader(file) ? - VladD

1 answer 1

You, as noted @VlaD code does not work, because instead

 new BufferedReader("D:\\Files") 

had to write

 new BufferedReader(file) 

And at the expense of similar methods, you can, for example, use a dirty hack with Scanner

 File dir = new File("D:\\Files"); for (File file : dir.listFiles()) { System.out.println("Content of " + file.getCanonicalPath() + ":"); Scanner scanner = new Scanner(new FileInputStream(file)).useDelimiter("\\A"); if (scanner.hasNext()) { System.out.println(scanner.next()); } } //FileInputStream по-хорошему нужно бы закрыть, но можно оставить и так — в finalize() блоке он сам себя закрывает.