java 程序调windows、linux命令行

来源:互联网 发布:中核华兴网络大学 编辑:程序博客网 时间:2024/06/09 15:46

java是可以调windows、linux命令行的,还可以运行一些小程序。


import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class test {public static void main(String[] args) {// System.out.println("hello jar");BufferedInputStream in = null;BufferedReader br = null;try {//调linux命令行并执行1.sh shell脚本 传两个参数,第一个“123”,第二个“2”Process pro = Runtime.getRuntime().exec("sh /home/hadoop/1.sh " + "123" + "2");// 调windows命令行,并运行notepad程序打开f盘下的a.txt文件。// Process pro = Runtime.getRuntime().exec("C:/Windows/System32/notepad.exe f:a.txt");// 定义shell返回值          String result = null;// 获取shell返回流          in = new BufferedInputStream(pro.getInputStream());          // 字符流转换字节流          br = new BufferedReader(new InputStreamReader(in));          // 这里也可以输出文本日志            String lineStr;          while ((lineStr = br.readLine()) != null) {              result = lineStr;          }          System.out.println(result);        // 关闭输入流  } catch (Exception e) {e.printStackTrace();}finally{try {br.close();in.close(); } catch (IOException e) {e.printStackTrace();}  }}}
windows下,将上述文件编译,并执行class文件。这些都是java基础知识,就不赘述了。

linux下,将class文件拷贝到linux下,1.sh的路径为"/home/hadoop/1.sh"

我的shell比较简单,就是将当前时间写入到一个log.txt文件中,sh脚本每执行一次,log中就多一行。

然后直接javac 执行class文件就可以了。


0 0