Java, UTF-8, and Windows console

后端 未结 5 649
清酒与你
清酒与你 2020-11-29 09:25

We try to use Java and UTF-8 on Windows. The application writes logs on the console, and we would like to use UTF-8 for the logs as our application has internationalized log

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 09:53

    Java on windows does NOT support unicode ouput by default. I have written a workaround method by calling Native API with JNA library.The method will call WriteConsoleW for unicode output on the console.

    import com.sun.jna.Native;
    import com.sun.jna.Pointer;
    import com.sun.jna.ptr.IntByReference;
    import com.sun.jna.win32.StdCallLibrary;
    
    /** For unicode output on windows platform
     * @author Sandy_Yin
     * 
     */
    public class Console {
        private static Kernel32 INSTANCE = null;
    
        public interface Kernel32 extends StdCallLibrary {
            public Pointer GetStdHandle(int nStdHandle);
    
            public boolean WriteConsoleW(Pointer hConsoleOutput, char[] lpBuffer,
                    int nNumberOfCharsToWrite,
                    IntByReference lpNumberOfCharsWritten, Pointer lpReserved);
        }
    
        static {
            String os = System.getProperty("os.name").toLowerCase();
            if (os.startsWith("win")) {
                INSTANCE = (Kernel32) Native
                        .loadLibrary("kernel32", Kernel32.class);
            }
        }
    
        public static void println(String message) {
            boolean successful = false;
            if (INSTANCE != null) {
                Pointer handle = INSTANCE.GetStdHandle(-11);
                char[] buffer = message.toCharArray();
                IntByReference lpNumberOfCharsWritten = new IntByReference();
                successful = INSTANCE.WriteConsoleW(handle, buffer, buffer.length,
                        lpNumberOfCharsWritten, null);
                if(successful){
                    System.out.println();
                }
            }
            if (!successful) {
                System.out.println(message);
            }
        }
    }
    

提交回复
热议问题