Enforce line separator when using Scanner class in Java


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 separator. 


    

Comments

Popular posts from this blog

VFD control with Arduino using RS485 link

How to get sinusoidal s-curve for a stepper motor

Stepper motor step signal timing calculation