Search code examples
javacsvformatinputstreamstringreader

New Line character with StringReader - \n is ignored?


I have this code:

String sampleString = "1223,4455,6667" + "\n" + "1223,4455,6667" + "\n";

BufferedReader reader = new BufferedReader(new StringReader(sampleString));
String line;
while ((line = reader.readLine()) != null) {
   if (line.trim().length() == 0) {
        continue;
   }
   logger.debug("CSVLIne:" + line);
}

I was expecting it to print two lines. But it shows all in one line. Anything wrong in this code?


Solution

  • You need to escape those newlines

        String sampleString = String.format("1223,4455,6667%n1223,4455,6667%n")
    

    The %n format specifier introduces platform dependent newline.