loadTable from a .csv file an newlines

Hello, I am loading from a .csv file the following table

[...]
04.jpg,"line1\nline2\nline3"
05.jpg,"line1\nline2\nline3"
06.jpg,"line1\nline2\nline3"
07.jpg,"line1\nline2\nline3"
08.jpg,"line1\nline2\nline3"
[...]

with the following fragment of code

  messagesFilename=language+".csv";
  Table table = loadTable(messagesFilename, "csv, newlines");      // i.e. file names 0.csv, 1.csv ...
  for (int index=0; index < table.getRowCount (); index++) {
    imageFilename[index]=table.getString(index, 0);
    imageTitle[index]=table.getString(index, 1);

    // Print what just loaded
    println(imageFilename[index] + " " + imageTitle[index]);
  }

I would expect output of the println to take \n into consideration and to be in the form of

[...]
04.jpg line1
line2
line3
05.jpg line1
line2
line3
[...]

but instead newlines (\n) are not properly interpreted and I get

[...]
04.jpg line1\nline2\nline3
05.jpg line1\nline2\nline3
06.jpg line1\nline2\nline3
07.jpg line1\nline2\nline3
08.jpg line1\nline2\nline3
[...]

Any suggestions?

Answers

  • Just a guess but it might be because the newlines \n are inside double quotes so are ignored.

  • Thank you very much for your suggestion. I tried even without quotes and I get the very same result.

  • Answer ✓

    Well, you read text which happens to have backslashes followed by the n character, you will find these sequences in the read text. There is no interpretation of these sequences.

    In a Java source, when you type \n, the compiler actually replace these sequences with the corresponding character. AFAIK, it happens even before compiling the code.

    If you want to replace these sequences in your strings by the real newline, you have to do it yourself:

    String s = "04.jpg line1\\nline2\\nline3"; // Have to double the backslashes in the code
    s = s.replaceAll("\\\\n", "\n");
    println(s);
    exit();
    
  • Thank you PhiLho! Your explanation and the sample piece of code you kindly provided simply solved the issue!

  • I wondered why I needed a quadruple backslash. Then I remembered that replaceAll() takes a regular expression as argument, which isn't needed for this usage. So you can change the line to the simpler:

    s = s.replace("\\n", "\n");
    
Sign In or Register to comment.