从命令行运行时瑞典语字符损坏

时间:2014-01-13 19:49:03

标签: java apache

我有一个简单的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();
}
}
}

如果我从包含“echoBåt”的批处理文件中运行它,则输出显示正确:

C:>echoBåt
BAT

但如果我用“cmd / cechoBåt”运行它,输出就会被破坏:

乙†吨

任何人都有任何想法?感谢。

在看到Jouni Aro的评论后,我使用'-Dfile.encoding ='设置做了更多测试(谢谢!)。以下是结果:

1)无设置(使用系统默认值):

Charset是:windows-1252

C:>echoBåt
BAT

Charset是:windows-1252

乙†吨

2)' - Dfile.encoding = UTF8':

Charset是:UTF-8

C:>echoB�t
B�t

Charset是:UTF-8

B�t

3)' - Dfile.encoding = ISO-8859-1':

Charset是:ISO-8859-1

C:>echoBåt
BAT

Charset是:ISO-8859-1

乙†吨

所以看起来charset在这里没有帮助?

2 个答案:

答案 0 :(得分:0)

尝试使用java "B\u00e5t"。问题可能是编辑器(java源代码)的编码与用于javac编译器的编码不同。

如果您使用“UTF-8”进行编辑,则必须

javac -encoding UTF-8 ...

答案 1 :(得分:0)

/**
 * This file created at 2016年1月11日.
 *
 * Copyright (c) 2002-2016 Honey, Inc. All rights reserved.
 */
package com.honey.proxy.helper;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.List;
import java.util.Properties;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.PumpStreamHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.honey.proxy.exception.CmdRunException;

/**
 * <code>{@link AbstractCommonExecs}</code>
 *
 * TODO : document me
 *
 * @author Honwhy
 */
public abstract class AbstractCommonExecs {

    private Logger log = LoggerFactory.getLogger(AbstractCommonExecs.class);
    private static final String DEFAULT_ENCODING = "UTF-8";
    private String encoding = DEFAULT_ENCODING;

    private String bin;
    private List<String> arguments;
    public AbstractCommonExecs(String bin, List<String> arguments) {
        this.bin = bin;
        this.arguments = arguments;
    }

    public ExecResult exec() throws CmdRunException{
        ExecResult er = new ExecResult();
        try {
            Executor executor = getExecutor();
            CommandLine cmdLine = getCommandLine();
            log.info("Executing script {}",cmdLine.toString());
            if(supportWatchdog()) {
                executor.setWatchdog(getWatchdog());
            }
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            PipedOutputStream outputStream = new PipedOutputStream();
            PipedInputStream pis = new PipedInputStream(outputStream);
            //ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream,errorStream);
            executor.setStreamHandler(streamHandler);
            int ret = executor.execute(cmdLine);

            BufferedReader br = new BufferedReader(new InputStreamReader(pis, getEncoding()));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while((line = br.readLine()) != null) {
                sb.append(line+"\n");
            }
            pis.close();
            String stdout = sb.toString();
            //String stdout = outputStream.toString(getEncoding());
            String stderr = errorStream.toString(getEncoding());
            er.setStderr(stderr);
            log.info("output from script {} is {}", this.bin, stdout);
            log.info("error output from script {} is {}", this.bin, stderr);
            log.info("exit code from script {} is {}", this.bin, ret);
            er.setStdout(stdout);
            er.setExitCode(ret);
            return er;
        } catch (ExecuteException e) {
            throw new CmdRunException("", e);
        } catch (IOException e) {
            throw new CmdRunException("", e);
        }

    }

    public Executor getExecutor() {
        Executor executor = new DefaultExecutor();
        executor.setWorkingDirectory(new File(this.bin).getParentFile());
        return executor;
    }
    public CommandLine getCommandLine() {
        String fullCommand = bin + join(arguments);
        return CommandLine.parse(fullCommand);
    }
    protected String join(List<String> arguments) {
        if(arguments == null || arguments.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for(String arg : arguments) {
            sb.append(" ").append(arg);
        }
        return sb.toString();
    }

    /**
     * @return the encoding
     */
    public String getEncoding() {
        return encoding;
    }

    /**
     * @param encoding the encoding to set
     */
    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    public abstract boolean supportWatchdog();
    public abstract ExecuteWatchdog getWatchdog();
}

//=====================
// Test class
/**
 * This file created at 2016年1月12日.
 *
 * Copyright (c) 2002-2016 Honey, Inc. All rights reserved.
 */
package com.honey.command;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.exec.ExecuteWatchdog;

import com.honey.proxy.helper.AbstractCommonExecs;
import com.honey.proxy.helper.ExecResult;

/**
 * <code>{@link GbkCommonExecs}</code>
 *
 * windows开发环境测试
 *
 * @author Honwhy
 */
public class GbkCommonExecs extends AbstractCommonExecs{

    /**
     * @param bin
     * @param arguments
     */
    public GbkCommonExecs(String bin, List<String> arguments) {
        super(bin, arguments);
    }

    /* (non-Javadoc)
     * @see com.bingosoft.proxy.helper.AbstractCommonExecs#supportWatchdog()
     */
    @Override
    public boolean supportWatchdog() {
        // TODO implement AbstractCommonExecs.supportWatchdog
        return false;
    }

    /* (non-Javadoc)
     * @see com.bingosoft.proxy.helper.AbstractCommonExecs#getWatchdog()
     */
    @Override
    public ExecuteWatchdog getWatchdog() {
        // TODO implement AbstractCommonExecs.getWatchdog
        return null;
    }

    public String getEncoding() {
        return "GBK";
    }
    public static void main(String[] args) {
        String bin = "ping";
        String arg1 = "127.0.0.1";
        List<String> arguments = new ArrayList<String>();
        arguments.add(arg1);
        AbstractCommonExecs executable = new GbkCommonExecs(bin, arguments);
        ExecResult er = executable.exec();
        System.out.println(er.getExitCode());
        System.out.println(er.getStdout());
        System.out.println(er.getStderr());
    }

}