ファイルから行を読み取ることによるJavaの進化

私の意見では、ファイルから行を読み取って印刷するタスクの例を使用して、単純でJavaの小作人開発者の生活がどのように変化したかについて、小さくて興味深い例を示します。



私たちの多くは覚えています

「Java 7より前」の苦痛:


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 } } } 


簡単にすることができます

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); } 


またはこのように:

  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


自動リソース管理(ARM)NIO.2およびStandardCharsetsをもたらしました。 サードパーティのライブラリを接続せずに、次のことが可能になりました。

  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 } 


またはさらに短い:

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


そして最後に:

Java 8


Stream APILambda式を使用して、これを1行で実行できます。

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


道徳:あなたが現代のJavaを持っている場合-あなたはうまくいく必要があり、悪くはありません。

あなたの注意とコーディングの成功に感謝します!

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


All Articles