我有一个简单的Java程序:瑞典字符损坏
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.LogOutputStream;
import org.apache.commons.exec.PumpStreamHandler;
public class test {
public static void main(String[] args) {
CommandLine commandLine = new CommandLine("c:/echo.bat");
/*CommandLine commandLine = new CommandLine("cmd.exe ");
commandLine.addArgument("/c");
commandLine.addArgument(" echo Båt"); */
DefaultExecutor executor = new DefaultExecutor();
try {
LogOutputStream output = new LogOutputStream() {
@Override
protected void processLine(String line, int level) {
System.out.println(line);
}
};
PumpStreamHandler streamHandler = new PumpStreamHandler(output);
executor.setStreamHandler(streamHandler);
executor.setExitValue(0);
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
executor.execute(commandLine, resultHandler);
} catch (ExecuteException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
如果我运行这个从含有批处理文件“回声BAT”,输出正确地显示:
Ç :>回波BAT
BAT
我若运行 “CMD/C回波BAT”,输出被损坏:
乙†吨
任何人有任何想法?谢谢。
在看到Jouni Aro的评论(谢谢!)后,我通过使用'-Dfile.encoding ='设置进行了更多测试。而这里的结果:
1)未设置(使用系统默认):
字符集是:窗口1252
C:>回声蝙蝠
蝙蝠
字符集是:窗口-1252
乙†吨
2) '-Dfile.encoding = UTF8':
Charset是:UTF-8
C:>回波B�t
B�t
Charset是:UTF-8
B�t
3)“ - 指定-Dfile.encoding = ISO-8859-1' :
Charset是:ISO-8859-1
C:>回声蝙蝠
蝙蝠
字符集是:ISO-8859-1
乙†牛逼
所以看起来字符集是没有帮助吗?
所不同的是在代码页。在批处理文件中,charset与cmd.exe将使用的相同,但是当您使用Java编写命令时,它使用的字符集与cmd.exe的默认字符集不匹配。 但我不确定,CommandLine对象的字符集将用于字符串,或者如果您可以将字符串转换为正确的字符集。 –