What separator should be used for each other line?

I have a text file containing data for every other line. I want to get the contents of each non-empty line. Given the entire text of the file, I first tried using myText.split("\n\n") . To my surprise, this will not work. I am working on windows.

+4
source share
1 answer

Windows uses CRLF as line breaks. And you crack on LF. This will not work.

Safe way:

 System.getProperty("line.separator"); 

to get the appropriate delimiter on your OS.

 String newLine = System.getProperty("line.separator"); myText.split("(?:" + newLine + ")+"); 

Perhaps you are reading a file created on another OS. Then the above method will not work. The best way is to use a character class with CR and LF , as pointed out by @Marko's comments:

 myText.split("[\r\n]+"); 
+5
source

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


All Articles