使用Runtime.exec在Linux中使用echo创建文件? [英] Create a file using Runtime.exec using echo in linux?

查看:92
本文介绍了使用Runtime.exec在Linux中使用echo创建文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中使用Runtime.exec时遇到问题,似乎有些命令可以工作,而其他命令则不能。例如,如果我运行

I'm having trouble using Runtime.exec in Java, it seems some commands work while others do not. For example if I run

echo some data > data.txt

在我的终端中,它可以正常工作,但是如果我尝试使用Java来做到这一点

In my terminal it works fine, however if I try and use Java to do this it doesn't work.

Runtime mRuntime = Runtime.getRuntime();
Process mProcess = mRuntime.exec("echo some data > data.txt");
mProcess.waitFor();

有什么理由吗?

推荐答案

echo 并不是真正的命令,因为它具有可以运行的二进制文件。它是shell的内置函数。

echo is not a real command in the sense that it has a binary that you can run. It is a built-in function of shells.

您可以尝试在Windows中运行像 cmd.exe 这样的shell。或 sh 在Linux / Mac / Unix中,然后传递命令以字符串形式运行。就像使用'bash'一样,您可以这样做:

You could try running a shell like cmd.exe in Windows or sh in Linux/Mac/Unix, and then passing the command to run as a string.. Like using 'bash', you can do this:

编辑,因为使用运行时

edit because redirection is a little different using Runtime

要正确进行重定向,您应该使用 exec 的形式,该格式采用 String []

To do redirection correctly, you should be using the form of exec that takes a String[].

这是一个适用于重定向的简单示例。

Here's a quick example that does work with redirection.

public class RunTest {
   public static void main(String[] args) throws Exception {
      String [] commands = { "bash", "-c", "echo hello > hello.txt" };
      Runtime.getRuntime().exec(commands);
   }
}

但是如果您只想创建文件,则可以可以使用Java自己的API创建文件,而不是使用 Runtime

But if you just wanted to create a file, you could create the file with Java's own API rather than use Runtime.

这篇关于使用Runtime.exec在Linux中使用echo创建文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆