如何在Java中为外部程序调用指定参数编码 [英] How to specify encoding of arguments for external program call in java

查看:54
本文介绍了如何在Java中为外部程序调用指定参数编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用包含德语字母的参数来启动外部程序,如下所示:

I want to start an external program with an argument which contains German letters, like this:

ProcessBuilder pb = new ProcessBuilder("myScript.sh", "argument_with_letters_äöü");     
Process p = pb.start();
    

我的JVM(在我的情况下为JBoss AS)以ISO 8859-15编码启动.但是,外部程序"myScript.sh"需要UTF-8.

My JVM (in my case a JBoss AS) is started with encoding ISO 8859-15. The external program 'myScript.sh' however expects UTF-8.

是否可以发送编码为UTF-8的参数?我在网上整理了一下,但没有找到答案.

Is there a way to send my argument encoded as UTF-8? I serched the web, but didn't find an answer.

推荐答案

查看

Looking at the code for java.lang.ProcessImpl (the package-private class that's responsible for starting processes in the non-Windows JRE - I assume you're not on Windows given the .sh extension), process arguments are always converted to bytes using the default encoding of the running JRE:

byte[][] args = new byte[cmdarray.length-1][];
// ...
for (int i = 0; i < args.length; i++) {
    args[i] = cmdarray[i+1].getBytes();

因此无法直接执行此操作.但是,如果您不需要将任何标准输入传递给 myScript.sh ,则可以使用 xargs 命令来解决该问题. xargs 的目的是从其标准输入中获取数据,并将其转换为另一个可执行文件的命令行参数:

so there's no way to do this directly. However, you may be able to work around it by using the xargs command provided you don't need to pass any standard input to myScript.sh. The purpose of xargs is to take data from its standard input and turn it into command line arguments to another executable:

// xargs -0 expects arguments on stdin separated by NUL characters
ProcessBuilder pb = new ProcessBuilder("xargs", "-0", "myScript.sh");
pb.environment().put("LANG", "de_DE.UTF-8"); // or whatever locale you require
Process p = pb.start();
OutputStream out = p.getOutputStream();
out.write("argument_with_letters_äöü".getBytes("UTF-8")); // convert to UTF-8
out.write(0); // NUL terminator
out.close();

(或者,如果您拥有 myScript.sh 的控制权,则修改 it 以期望其文件名位于stdin上而不是作为参数)

(or if you have control of myScript.sh, then modify it to expect its file names on stdin rather than as arguments)

这篇关于如何在Java中为外部程序调用指定参数编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆