Posts

Showing posts from November, 2022

Learning new Java tools

Image
 While I have been using Java for almost 30 years, every now and then, I find new things I was not aware of in the Java toolset. Sometimes it is due to new libraries/classes; other times, it is brand-new tools.  I have been using Python lately, and I have found the use of an interpreter for testing code snippets very helpful. Unfortunately, that is not something you can do with Java, right? Well, that was the case till jshell was released. But what is jshell , let us say it is a Java's REPL. Like in Python, you can have an interactive session with the language interpreter, but now using Java.  How does it work? jshell is a command line tool you can find in OpenJDK or in Oracle's JDK since JDK 9 .  Not much different than Python, right? And you can ignore the semicolon at the end of each line :-) But it is more than just a calculator; you can instantiate any type of object, and it all persists in memory the whole session. It feels great to be able to have access to all the progr

Enforce line separator when using Scanner class in Java

Image
Parsing the data stream from a file or a socket can be very easy using the Scanner class. However, if you need to honor a given line separator sequence, using the nextLine() method can be problematic. The reason being the nextLine() method can accept a variety of line separators (like "\r\n", "\n", or "\r"). That behavior might be ok most of the time, but sometimes you may want to be sure that the line you are reading is precisely delimited by a given line separator and only by that one. The solution that works for me is not to use nextLine() but next()  after changing the token delimiter to the desired line separator. For example, I want to get a line read from the input delimited by "\r\n" only. ...  Scanner sc = new Scanner(s.getInputStream()).useDelimiter("\r\n");  String line = sc.next(); // before this was sc.nextLine(); ... Now full lines can be read as if they were a single token as now tokens are separated by the desired line s