运行 shell 在 java 中观看服务
Run shell inside watch service in java
我想 运行 shell watch service class 脚本到 运行 shell 新文件添加到文件夹后。
手表服务运行良好,但当我想添加 Runtime.getRuntime().exec("home/user/test.sh")
;我收到错误。
我只是在这之后添加运行时:
// Dequeueing events
Kind<?> kind = null;
for(WatchEvent<?> watchEvent : key.pollEvents()) {
// Get the type of the event
kind = watchEvent.kind();
if (OVERFLOW == kind) {
continue; //loop
} else if (ENTRY_CREATE == kind) {
// A new Path was created
Path newPath = ((WatchEvent<Path>) watchEvent).context();
// Output
System.out.println("New path created: " + newPath);
Runtime.getRuntime().exec("home/user/test.sh")
我必须做什么?
我认为 运行 脚本的问题与 WatchService
无关,因为你没有 post 实际抛出的异常(这会有很大帮助)我可以只是猜测出了什么问题,所以请检查一下:
脚本没有执行权限(可以通过 chmod +x path/to/script.sh
轻松修复)- 在这种情况下,您会得到 IOException
以及类似 Permission denied
或类似的消息
系统找不到您的脚本,因为您使用的是相对路径(脚本名称开头没有 /
),在这种情况下,ether 使用完整的脚本名称,例如/home/user/foo/script.sh
或使用正确的相对路径 ../foo/script.sh
- 您应该通过 exec (How do I check if a file exists in Java?)
检查 运行 之前脚本是否存在
注意脚本可能会在 运行 Java 程序的工作目录下被调用 - 所以你应该将新创建的文件路径作为参数传递给脚本以使其独立于它的位置
我遵循了您使用代码的教程:
if (OVERFLOW == kind) {
continue; //loop
} else if (ENTRY_CREATE == kind) {
// A new Path was created
Path newPath = ((WatchEvent<Path>) watchEvent).context();
// Output
System.out.println("New path created: " + newPath);
Runtime.getRuntime().exec(new String[] { "/home/xxx/foo.sh", newPath.toString() });
}
和脚本:
#!/bin/bash
echo "FILE CREATED: " >> /home/xxx/watch_dir.log
并且它没有任何错误。
我想 运行 shell watch service class 脚本到 运行 shell 新文件添加到文件夹后。
手表服务运行良好,但当我想添加 Runtime.getRuntime().exec("home/user/test.sh")
;我收到错误。
我只是在这之后添加运行时:
// Dequeueing events
Kind<?> kind = null;
for(WatchEvent<?> watchEvent : key.pollEvents()) {
// Get the type of the event
kind = watchEvent.kind();
if (OVERFLOW == kind) {
continue; //loop
} else if (ENTRY_CREATE == kind) {
// A new Path was created
Path newPath = ((WatchEvent<Path>) watchEvent).context();
// Output
System.out.println("New path created: " + newPath);
Runtime.getRuntime().exec("home/user/test.sh")
我必须做什么?
我认为 运行 脚本的问题与 WatchService
无关,因为你没有 post 实际抛出的异常(这会有很大帮助)我可以只是猜测出了什么问题,所以请检查一下:
脚本没有执行权限(可以通过
chmod +x path/to/script.sh
轻松修复)- 在这种情况下,您会得到IOException
以及类似Permission denied
或类似的消息系统找不到您的脚本,因为您使用的是相对路径(脚本名称开头没有
/
),在这种情况下,ether 使用完整的脚本名称,例如/home/user/foo/script.sh
或使用正确的相对路径../foo/script.sh
- 您应该通过 exec (How do I check if a file exists in Java?) 检查 运行 之前脚本是否存在
注意脚本可能会在 运行 Java 程序的工作目录下被调用 - 所以你应该将新创建的文件路径作为参数传递给脚本以使其独立于它的位置
我遵循了您使用代码的教程:
if (OVERFLOW == kind) {
continue; //loop
} else if (ENTRY_CREATE == kind) {
// A new Path was created
Path newPath = ((WatchEvent<Path>) watchEvent).context();
// Output
System.out.println("New path created: " + newPath);
Runtime.getRuntime().exec(new String[] { "/home/xxx/foo.sh", newPath.toString() });
}
和脚本:
#!/bin/bash
echo "FILE CREATED: " >> /home/xxx/watch_dir.log
并且它没有任何错误。