问题
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();
My JVM (in my case a JBoss AS) is started with encoding ISO 8859-15. The external program 'myScript.sh' however expects UTF-8.
Is there a way to send my argument encoded as UTF-8? I serched the web, but didn't find an answer.
回答1:
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();
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();
(or if you have control of myScript.sh
, then modify it to expect its file names on stdin rather than as arguments)
来源:https://stackoverflow.com/questions/26827546/how-to-specify-encoding-of-arguments-for-external-program-call-in-java