从Java执行sh文件 [英] Execute sh file from Java

查看:555
本文介绍了从Java执行sh文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过以下代码(CentOS计算机btw)执行一个sh文件

I am trying to execute an sh file via the following code (CentOS machine btw)

Runtime.getRuntime().exec("sh " + file.getPath());

我在Windows上使用此代码,效果很好

I use this code for windows and it works fine

Runtime.getRuntime().exec("cmd /c start " + file.getPath());

是因为我在.sh文件中使用Screen吗?我也在使用java命令来启动服务器,所以也许我需要包括这些?

Could it be because I'm using Screen in the .sh file? I am also using the java command to start the server so maybe I need to include these?

这是sh文件的内容

#!/bin/sh
BINDIR=$(dirname "$(readlink -fn "$0")")
cd "$BINDIR"
screen -S PrivateServer java -Xms2048M -Xmx2048M -jar somejar.jar -o true

我也在关闭钩子上运行此代码,这可能是问题吗?这是因为该软件是游戏服务器,并且使用户可以使用重新启动命令或使其自动重新启动,而无需自行设置任何内容.

I am also running this code from a shutdown hook, could this be the issue? This is intended because the software is a game server and it is intended so that the user can use a restart command or have it auto restart without needing to setup anything them self.

我决定将错误输出到文本文件,并发现此必须连接到终端".有任何想法吗?我相信这与使用屏幕有关.

I decided to output the errors to a text file and found this "Must be connected to a terminal." any ideas? I believe this is an issue to do with using screen.

推荐答案

由于您确认文件具有可执行权限,因此请尝试按以下方式传递参数:

Since you confirmed that the file has executable permission, try to pass the argument as follows:

Runtime.getRuntime().exec(new String[]{"/bin/sh" ,"-c", file.getPath()});

因此主要提供sh的完整路径并使用-c

So mainly provide the complete path for sh and use -c

这篇关于从Java执行sh文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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