muốn chạy được trên powershell phải xài jna gọi hàm native của Windows WriteConsoleW :V
Cấu trúc project
D:PROGJAVATEST01 │ README.md │ ├───lib │ jna.jar │ └───src ChuongTrinhDauTien.java Console.java
Download file jna.jar ở đây và bỏ vào thư mục lib
Nguồn của Console.java “chôm” ở đây, có sửa Native.loadLibrary đã deprecated lại thành Native.load và thêm package console.windows
package console.windows; 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.load(“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); } }
Nguồn ChuongTrinhDauTien.java (thêm package main):
package main; import java.util.*; import java.lang.*; import java.nio.charset.*; import console.windows.*; public class ChuongTrinhDauTien { public static void main(String[] args) { System.out.println(“Chào bạn và mọi người.”); System.out.println(Arrays.toString(“ắ”.getBytes())); System.out.println(“u1EAF”); Console.println(“Chào bạn và mọi người.”); } }
Build và run
Compile
Mở Powershell tới thư mục project (ở đây là D:PROGJAVATEST01), gõ:
javac -encoding utf8 -classpath “lib*” -d “build” “src*.java”
javac sẽ compile ra các class:
D:PROGJAVATEST01BUILD ├───console │ └───windows │ Console$Kernel32.class │ Console.class │ └───main ChuongTrinhDauTien.class
Build jar file
cd build; jar cvf “001.jar” *
jar sẽ gom các class lại thành 1 file jar, ở đây đặt tên là 001.jar
D:PROGJAVATEST01BUILD │ 001.jar │ ├───console │ └───windows │ Console$Kernel32.class │ Console.class │ └───main ChuongTrinhDauTien.class
Run
Nếu ở trong thư mục build (D:PROGJAVATEST01BUILD) thì gõ:
java -cp “001.jar;..lib*” main.ChuongTrinhDauTien
Nếu ở trong thư mục project (D:PROGJAVATEST01) thì gõ:
java -cp “build01.jar;lib*” main.ChuongTrinhDauTien
Nó sẽ in ra:
Chào b?n và m?i ng??i. [63] ? Chào bạn và mọi người.
Chạy trên Powershell hay Cmd, bất kể code page nào thì dòng cuối cùng cũng in ra chữ tiếng Việt được