How can I change the Standard Out to “UTF-8” in Java

前端 未结 3 1547
忘掉有多难
忘掉有多难 2020-12-20 22:49

I download a file from a website using a Java program and the header looks like below

Content-Disposition attachment;filename=\"Textkürzung.asc\";

3条回答
  •  心在旅途
    2020-12-20 23:27

    The default encoding of System.out is the operating system default. On international versions of Windows this is usually the windows-1252 codepage. If you're running your code on the command line, that is also the encoding the terminal expects, so special characters are displayed correctly. But if you are running the code some other way, or sending the output to a file or another program, it might be expecting a different encoding. In your case, apparently, UTF-8.

    You can actually change the encoding of System.out by replacing it:

    try {
        System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out), true, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new InternalError("VM does not support mandatory encoding UTF-8");
    }
    

    This works for cases where using a new PrintStream is not an option, for instance because the output is coming from library code which you cannot change, and where you have no control over system properties, or where changing the default encoding of all files is not appropriate.

提交回复
热议问题