Most probably a FileWriter is not meant to write to a console, but it does.
So I use it for easy switching between the two destinations.
I only wonder what character conversion takes place when it comes to 8-bit
characters.
Run the following code without any parameter and you will see the difference
between System.out.println(...) and the FileWriter's output.
Run the code giving a file specification as parameter and you will see that the
FileWriter works as expected.
I tried to:
- translate the test string to UTF-8
- passing a character set
(StandardCharsets.UTF_8, Charset.defaultCharset())to theFileWriter - specifying
FileDescriptor.outfor theFileWriter
but to no avail.
Other solutions are ready-at-hand, but still I would like to know whether using a FileWriter is possible.
import java.io.*;
import java.nio.charset.*;
public class ConsoleOutput {
static public void main(String args[]) {
String s = "Hello äöüß áàâçéèê";
String filespc = args.length==0 ? "CON:" : args[0];
boolean console= filespc.equals("CON:"); // For both cmd.exe & PowerShell.
try (BufferedWriter outfile= new BufferedWriter(new FileWriter(filespc))) {
// if (console) s = new String(s.getBytes(StandardCharsets.UTF_8),
// StandardCharsets.UTF_8);
System.out.println(s);
outfile.write(s);
outfile.newLine();
}
catch (IOException e) {
System.out.println(e);
}
}
}