Home > Back-end >  \n (new line) not working in creating text file
\n (new line) not working in creating text file

Time:09-17

I want to download the text file by clicking on button, everything is working fine as expected. But the problem is the data I want to insert in text file is just one line.

String fileContent = "Simple Solution \nDownload Example 1"; here, \n is not working. It resulting in output as:

Simple Solution Download Example 1

Code snippets:

interface:

enter image description here

interface implementation in my service class:

enter image description here

controller:

enter image description here

CodePudding user response:

Don't use hardcoded \n nor \r\n - line-separators are platform-specific (Windows differs to all other OS).

What you can do is:

  1. Use System.lineSeparator()
  2. Build content with String.format() and replace \n with %n

CodePudding user response:

The main problem is that the server computer and client computer are basically independent with respect to character set encoding and line separators. Defaults will not do.

  1. As we are living in a Windows centric world (I am a linuxer), user "\r\n".

  2. Then java can mix any Unicode script. A file does not have info on its encoding. If it originates on an other computer/platform, that raises problems.

     String fileContent = "Simple Solution façade, mañana, €\r\n"
           "Download Обичам ĉĝĥĵŝŭ Example 1";
    

    So the originating computer explicitly define the encoding. It should not do:

     fileContent.getBytes(); // Default platform encoding Charset.defaultCharset().
    

    So the originating computer can do:

     fileContent.getBytes(StandardCharsets.UTF_8); // UTF-8, full Unicode.
     fileContent.getBytes("Windows-1252); // MS Windows Latin 1, some ? failures.
    

    The contentType can be set appropriately with "text/plain;charset=UTF-8" or for Windows-1252 "text/plain;charset=ISO-8859-1".

    And from that byte[] you should take the .length for the contentLength.

  3. Writing to the file can use Files.writeString

    In that case use Files.size(exportedPath) for the content length.

  4. Files.newInputStream(exportedPath) is the third goodie from Files.

  • Related