tof*_*der 12 java windows console utf-8
我们尝试在Windows上使用Java和UTF-8.应用程序在控制台上写入日志,我们希望将UTF-8用于日志,因为我们的应用程序具有国际化日志.
可以配置JVM,使其-Dfile.encoding=UTF-8作为JVM的参数生成UTF-8 .它工作正常,但Windows控制台上的输出是乱码.
然后,我们可以将控制台的代码页设置为65001(chcp 65001),但在这种情况下,.bat文件不起作用.这意味着当我们尝试通过我们的脚本(名为start.bat)启动我们的应用程序时,绝对没有任何反应.命令simple返回:
C:\Application> chcp 65001
Activated code page: 65001
C:\Application> start.bat
C:\Application>
Run Code Online (Sandbox Code Playgroud)
但没有chcp 65001,没有问题,应用程序可以启动.
有关于此的任何提示?
小智 7
Windows上的Java默认情况下不支持unicode输出.我已经通过调用带有JNA库的Native API编写了一个变通方法.该方法将在控制台上调用WriteConsoleW来进行unicode输出.
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19721 次 |
| 最近记录: |