Eclipse下使用Runtime.getRuntime().exec启动java程序的问题

本文介绍了解决在Eclipse环境下使用Runtime.getRuntime().exec调用其他Java程序时遇到的问题。通过调整classpath和指定类的完整路径,成功实现了跨类加载启动。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:http://blog.sina.com.cn/s/blog_6b96eae10100ok01.html


天在Eclipse中写了用到 Runtime.getRuntime().exec("java MyTest"); 来启动一个新的java程序,无奈却无法启动MyTest类。

  而这个程序在cmd中是可以完全正常运行的。于是我将MyTest.class(除去包名)复制到此工程的根目录下,突然发现MyTest程序启动

了!

   我由此得出结论,使用Runtime.getRuntime().exec来启动其他java程序时,  java虚拟机是在工程的根目录下开始查找这个类的,而这个类实际存在于bin目录下面。这时只要在命令中加入classpath的设置信息皆可,另外需 加上包名。

最后修改代码如下:

 Runtime.getRuntime().exec("java -classpath H:\\workspace\\javawork\\bin  cn.itcast.io.MyTest");

或者

Runtime.getRuntime().exec("java -classpath .\\bin   cn.itcast.io.MyTest");  .代表当前目录.

或者

Runtime.getRuntime().exec("java -classpath bin   cn.itcast.io.MyTest");

程序正常运行!


import java.util.Scanner; import java.util.Timer; import java.util.TimerTask; public class AutoShutdown { private static Timer shutdownTimer; private static boolean isCancelled = false; public static void main(String[] args) { System.out.println("=== 定时关机程序 ==="); System.out.print("请输入关机倒计时(秒): "); Scanner scanner = new Scanner(System.in); int seconds = scanner.nextInt(); // 启动关机倒计时 startShutdownCountdown(seconds); // 监听用户取消输入 monitorCancelOption(scanner); scanner.close(); } private static void startShutdownCountdown(int seconds) { shutdownTimer = new Timer(); final int[] remaining = {seconds}; shutdownTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (isCancelled) { cancelShutdown(); return; } System.out.printf("系统将在 %d 秒后关机...\n", remaining[0]); // 倒计时结束执行关机 if (remaining[0] <= 0) { try { Runtime.getRuntime().exec("shutdown -s -t 0"); System.out.println("正在执行关机..."); shutdownTimer.cancel(); } catch (Exception e) { System.err.println("关机命令执行失败: " + e.getMessage()); } return; } // 倒计时最后10秒特殊提示 if (remaining[0] <= 10) { System.out.println(">>> 即将关机! 输入 'cancel' 取消 <<<"); } remaining[0]--; } }, 0, 1000); // 每秒执行一次 } private static void monitorCancelOption(Scanner scanner) { new Thread(() -> { while (true) { String input = scanner.nextLine().trim(); if ("cancel".equalsIgnoreCase(input)) { isCancelled = true; break; } } }).start(); } private static void cancelShutdown() { try { Runtime.getRuntime().exec("shutdown -a"); System.out.println("关机已取消"); shutdownTimer.cancel(); } catch (Exception e) { System.err.println("取消关机失败: " + e.getMessage()); } } } 代码报错 定时.java:5: 错误: 类 AutoShutdown 是公共的, 应在名为 AutoShutdown.java 的文件中声明 public class AutoShutdown { ^ 注: 定时.java使用或覆盖了已过时的 API。 注: 有关详细信息, 请使用 -Xlint:deprecation 重新编译。 1 个错误
06-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值