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:
interface implementation in my service class:
controller:
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:
- Use
System.lineSeparator()
- 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.
As we are living in a Windows centric world (I am a linuxer), user
"\r\n"
.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.Writing to the file can use Files.writeString
In that case use
Files.size(exportedPath)
for the content length.Files.newInputStream(exportedPath)
is the third goodie from Files.