【问题标题】:Java can't get full error when running an external command运行外部命令时 Java 无法得到完整错误
【发布时间】:2013-01-10 04:00:14
【问题描述】:

我正在尝试在 java 中编译 typescript 文件。

这是一个有错误的“.ts”文件:

alert("hello, typescript");
errrrrrrrrrrrrrrrrrrrrrrrrrror

当我在 windows shell(cmd) 中编译时:

tsc hello.ts

它会报告错误消息:

E:/WORKSPACE/test/typescripts/hello.ts(2,0): The name 'errrrrrrrrrrrrrrrrrrrrrrrrror' 
does not exist in the current scope

但是当我在 java 中这样做时:

String cmd = "cmd /C tsc hello.ts";
Process p = Runtime.getRuntime().exec(cmd);
String out = IOUtils.toString(p.getInputStream());
String error = IOUtils.toString(p.getErrorStream());
System.out.println("### out: " + out);
System.out.println("### err: " + error);

打印出来:

### out:
### err: E:/WORKSPACE/test/typescripts/hello.ts(2,0):

您可以看到没有捕获到详细错误。我的代码哪里出了问题?


更新

我只是确定MS提供的tsc.exe没有这个问题,我在这个问题中运行的是从npm安装的tsc.cmdnpm install typescript

【问题讨论】:

  • 试试 apache common exec,我认为这应该可以帮助你。
  • 恐怕是typescript的编译器tsc的问题。由于我尝试了Java以外的一些工具(grunt.js),他们也只能得到第一行错误消息。
  • 我只是确定MS提供的tsc.exe没有这个问题,我在这个问题中运行的是从npm安装的tsc.cmdnpm install typescript
  • 如果有帮助,这是一个从 java 进行 typescript 编译的项目:github.com/martypitt/typescript4j

标签: java process cmd


【解决方案1】:

您是否尝试过使用原始 Process/ProcessBuilder 组合?

ProcessBuilder pb = new ProcessBuilder("cmd /C tsc hello.ts");

//merge error output with the standard output
pb.redirectErrorStream(true);

Process p = pb.start();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.forName("UTF-8")))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
}

【讨论】:

【解决方案2】:

我只是花了几个小时来解决同样的问题。

最后我通过在命令行中添加"2> errorfile.txt" 来解决这个问题。这会将stderr 重定向到一个文件,然后我读取并打印该文件。

【讨论】:

    猜你喜欢
    • 2014-06-08
    • 2019-01-15
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 2020-01-09
    • 2021-02-28
    • 2021-01-18
    相关资源
    最近更新 更多