java调用shell脚本小demo

复制指定文件
cpp.sh:

[root@localhost soft]# vim cpp.sh
#!/bin/bash


name="$1"
\cp /home/soft/test/${name} /opt/
echo "co ok"
~
~

java:

public class YY {
public static void main(String[] args) throws IOException {
System.out.println("java linux starting 。。。。");
long start=System.currentTimeMillis();
//shell脚本地址
String filepath = "/home/soft/test";
String fileNmae=UUID.randomUUID().toString().replace("-","");
filepath=filepath+"/"+fileNmae;
File file = new File(filepath);
file.createNewFile();
OutputStream outputStream=new FileOutputStream(file);
String text="测试java调用shell脚本\n";
outputStream.write(text.getBytes());
outputStream.flush();
outputStream.close();
Runtime runtime = Runtime.getRuntime();
//shell脚本加参数 fileNmae
String path="/home/soft/cpp.sh "+fileNmae;
try {
Process ss = runtime.exec(path);
System.out.println("复制文件:"+filepath);
System.out.println(System.currentTimeMillis()-start);
System.out.println("java linux ending ....");
} catch (IOException e) {
e.printStackTrace();
System.out.println("java linux exception....");
}
}
}

执行效果:
[root@localhost soft]# java YY
java linux starting 。。。。
复制文件:/home/soft/test/0fcdde746dda4f588e404ab5ef9adec0
177
java linux ending ....
[root@localhost soft]# ll /opt/
total 8
-rw-r--r--. 1 root root 28 May 11 20:16 0fcdde746dda4f588e404ab5ef9adec0
drwxr-xr-x. 2 root root 4096 Nov 22 2013 rh
[root@localhost soft]#

 

posted @ 2019-05-12 11:20  洞玄巅峰  阅读(406)  评论(0编辑  收藏  举报