0

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 the FileWriter
  • specifying FileDescriptor.out for the FileWriter

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);
    }

  }
}
Amal K
  • 4,359
  • 2
  • 22
  • 44
Jörg
  • 214
  • 1
  • 9
  • On macOS terminal, replacing `CON:` with `/dev/stdout`, the code works fine, producing two lines of output that are the same. I think it's an OS/console issue. What unexpected output did your code produce? – Sweeper Jun 19 '21 at 06:16
  • @Sweeper Thank you for testing. I receive on Windows10 "Hello õ÷³▀ ßÓÔþÚÞÛ" – Jörg Jun 19 '21 at 06:22
  • Try getting the console encoding with the code in [this answer](https://stackoverflow.com/a/6173066/5133585). See if it is UTF8. If it is not, try giving that charset to the `FileWriter`. If it is, then I don't know. – Sweeper Jun 19 '21 at 06:28
  • @Sweeper It is the system's default character set (Cp1252), which is also the default for FileWriter. I had already tried to explicitly pass the system's default character set to FileWriter, but there was no change. Thank you anyhow. – Jörg Jun 19 '21 at 06:52

0 Answers0