为什么我不能在 java 运行时使用日志文件

发布于 2024-09-15 19:49:41 字数 308 浏览 10 评论 0原文

我有(在java中),

rt.exec("qq.exe -i ..(some other parameters) > qq.log");//*1

当我运行 qq.exe -i ..(一些其他参数)>终端中的 qq.log 工作正常并正确保存 qq.log 文件。

但是使用 rt.exec (*1) 不起作用。 “> qq.log”部分导致问题。当我删除该部分时,rt.exec (*1) 可以工作,但这次我无法获得 qq.log 文件。

是什么原因导致这个问题以及有什么解决办法吗?

I have (in java),

rt.exec("qq.exe -i ..(some other parameters) > qq.log");//*1

when I run qq.exe -i ..(some other parameters) > qq.log in terminal It works fine and keeps the qq.log file correctly.

However using rt.exec (*1) doesnt work. " > qq.log" part causes problem. When I delete that part rt.exec (*1) works but I cant have qq.log file this time.

What causes this problem and Is there any soln??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你与清晨阳光 2024-09-22 19:49:41

rt.exec() 无法执行 sh/bat 代码。它只是调用另一个程序。当您尝试使用 shell 特有的 > 符号重定向 qq.exe 的输出流时,java 不明白该怎么做。

另一种方法是,当您使用 exec 方法执行某个程序时,获取 进程rt.exec()返回。
进程 可以为您提供应用程序的OutputStream、应用程序的InputStream,甚至启动应用程序的ErrorStream。

使用InputStream,您可以以编程方式读取qq.exe的结果,您所要做的就是将其写入文件中。

rt.exec() can't execute sh/bat code. It's just invoking another program. When you try to redirect the output stream of qq.exe with the > symbol, which is specific to shell, java doesn't understand what to do.

An alternative is when you execute some program with the exec method, get the Process returned by rt.exec().
A Process can give you an OutputStream to the application, an InputStream from the application and even an ErrorStream for a started application.

With the InputStream, you can programmatically read the result of qq.exe and all you have to do is to write this into a file.

不回头走下去 2024-09-22 19:49:41

Java 7 添加了 ProcesBuilder.Redirect 类,允许将输入/输出/错误流重定向到文件或从文件重定向。它可以这样使用:

    ProcessBuilder builder = new ProcessBuilder("cat", "/proc/meminfo");
    // Append all errors from process to log file:
    builder.redirectError(Redirect.appendTo(new File("/tmp/my.log")));
    Process process = builder.start();

使用相应的方法可以重定向输入和输出。完整的示例如下:在 Java 7 中运行外部进程

Java 7 added ProcesBuilder.Redirect class that allows to redirect input/output/error streams to/from files. It can be used like this:

    ProcessBuilder builder = new ProcessBuilder("cat", "/proc/meminfo");
    // Append all errors from process to log file:
    builder.redirectError(Redirect.appendTo(new File("/tmp/my.log")));
    Process process = builder.start();

Using corresponding methods you can redirect input and output. The full example is here: Run external process in Java 7.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文