📜 ⬆️ ⬇️

Java evolution by reading lines from a file

Let me give you a small and interesting, in my opinion, example of how the life of a simple Java developer peasant has changed, using the example of reading and printing lines from a file.



Many of us remember
')

'to java 7' torment:


BufferedReader reader = null; try { reader = new BufferedReader( new InputStreamReader( new FileInputStream(FILE_NAME), Charset.forName("UTF-8"))); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { // log error } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // log warning } } } 


which could ease, except

Apache Commons IO


  InputStreamReader in = null; try { in = new InputStreamReader(new FileInputStream(new File(FILE_NAME)), Charsets.UTF_8); LineIterator it = new LineIterator(in); while (it.hasNext()) { System.out.println(it.nextLine()); } } catch (IOException e) { // log error } finally { IOUtils.closeQuietly(in); } 


Or even like this:

  LineIterator it = null; try { it = FileUtils.lineIterator(new File(FILE_NAME), "UTF-8"); while (it.hasNext()) { System.out.println(it.nextLine()); } } catch (IOException e) { // log error } finally { if (it != null) { it.close(); } } 

Java 7


brought automatic resource management (ARM) , NIO.2 and StandardCharsets . Now, without connecting third-party libraries, it is possible to do:

  try (BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream(FILE_NAME), StandardCharsets.UTF_8))){ String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { // log error } 


or even shorter:

  List<String> lines = Files.readAllLines(Paths.get(FILE_NAME), StandardCharsets.UTF_8); for(String line: lines){ System.out.println(line); } 


And finally:

Java 8


with its Stream API and Lambda expressions allowed to do it in one line:

  Files.lines(Paths.get(FILE_NAME), StandardCharsets.UTF_8).forEach(System.out::println); 


Moral: if you have modern Java, you have to do it well and don’t do it badly.

Thank you for your attention and success in coding!

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


All Articles