-- Leo's gemini proxy

-- Connecting to republic.circumlunar.space:1965...

-- Connected

-- Sending request

-- Meta line: 20 text/gemini

Iterating over the lines of a file in Java


If you're trying to write a standard command-line tool in Java you are going to experience pain.


In Python, if we want to do something with each line on input to your program, we can do something like:


import sys
for ln in sys.stdin:
   print(ln)  # (We have an extra newline but who's counting?)


In Java, after some fighting, the two closest alternatives I can find are:


import java.util.Scanner;
class IterateInputScanner {
   public static void main(String[] args) {
       for(String ln : (Iterable)(() -> new Scanner(System.in).useDelimiter("\n"))) {
           System.out.println(ln);
       }
   }
}


or, less fashionably, and even more horribly:


import java.io.BufferedReader;
import java.io.InputStreamReader;
class IterateInputReader {
   public static void main(String[] args) throws java.io.IOException {
       BufferedReader reader =
           new BufferedReader(new InputStreamReader(System.in));
       String ln;
       while((ln = reader.readLine()) != null) {
           System.out.println(ln);
       }
   }
}


Note that if you are reading from a stream other than stdin you will probably want to wrap this in a try -with-resources to close the stream when you've finished.


Take your pick, and I hope it saves you some fighting.


Originally posted at 2017-02-09 13:25:48+00:00. Automatically generated from the original post : apologies for the errors introduced.


original post

-- Response ended

-- Page fetched on Sun May 19 06:42:08 2024