mbrc mbrc - 4 months ago 39
Linux Question

Java FileUtils.writeLines in ANSI format with New line as CR LF

I would like to write file in JAVA


  • Encoding : ANSI

  • New line: CR LF



Example:

FileUtils.writeLines(new File(baseFolder.getAbsolutePath() + File.separatorChar + filename), data);


I am using
Apache FileUtils.writeLines
but it is always in
UTF-8
not
ANSI
and new line as
LF
and not
CR LF
?

Server is
Linux
not
Windows

Answer

Invoke the appropriate overload of writeLines, with the parameters in the right order:

public static void writeLines(File file,
          String encoding,
          Collection<?> lines,
          String lineEnding)
                   throws IOException

e.g.

FileUtils.writeLines(
    new File(baseFolder.getAbsolutePath(), filename),
    "Cp1252",
    data,
    "\r\n");

Note that Windows ANSI isn actually called Cp1252 in Java, according to this answer.


You are passing the encoding as the last parameter to this overload, which is actually the line ending parameter.

public static void writeLines(File file,
          Collection<?> lines,
          String lineEnding)
                   throws IOException