我有一個簡單的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對象的字符集將用於字符串,或者如果您可以將字符串轉換爲正確的字符集。 –