java执行多条linux命令

简单介绍一下使用java通过Runtime.getRuntime().exec(cmd)方法调用linux命令,以压缩文件的使用场景为例

方法一,通过数组调用:

	public static void zipFile(String filename, String path) {
		File[] file = new File(path).listFiles();
		File zipfile = new File(path + filename + ".zip");
		if(zipfile.exists())
			return;
		if(file != null && file.length > 0){
			try {
				String[] cmd = new String[]{"sh", "-c", "zip -m " + path + filename + ".zip " + path + "*" + filename + "*.txt"};
				Process p = Runtime.getRuntime().exec(cmd);
				//shell脚本中有echo或者print输出, 会导致缓冲区被用完,程序卡死! 为了避免这种情况, 
				//一定要把缓冲区读一下 reader.readLine() 读出即可,如果需要输出的话可以使用StringBuilder 
				//进行拼接然后输出
	    		BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
			    String line;
			    StringBuilder sb = new StringBuilder();
			    while((line = reader.readLine()) != null) {
			        sb.append(line).append("\r\n");
			    }
	            p.waitFor();
	            p.destroy();
			} catch (Exception e1) {
				logger.error("IOException", e1);
			}
		}else
			logger.info("无待压缩文件-------------------");
	}

方法二,调用多条linux命令:

    public static void zipFile(String filename, String paht) {
    	File[] file = new File(paht).listFiles();
		File zipfile = new File(paht + filename + ".zip");
		if(zipfile.exists())
			return;
		if(file != null && file.length > 0){
			Runtime run = Runtime.getRuntime();
	        File wd = new File("/bin");
	        Process proc = null;
	        try {
	            proc = run.exec("/bin/bash", null, wd);
	            if (proc != null) {
		            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
		            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
		            out.println("cd " + paht);
		            out.println("pwd");
		            out.println("zip -m " + filename + ".zip *" + filename + "*.txt");
		            out.println("exit");//这个命令必须执行,否则in流不结束。
		            //shell脚本中有echo或者print输出, 会导致缓冲区被用完,程序卡死! 为了避免这种情况, 
				    //一定要把缓冲区读一下 reader.readLine() 读出即可,如果需要输出的话可以使用StringBuilder 
				    //进行拼接然后输出
		            String line;
		            StringBuilder sb = new StringBuilder();
	                while ((line = in.readLine()) != null) {
	                	sb.append(line).append("\r\n");
	                }
	                proc.waitFor();
	                in.close();
	                out.close();
	                proc.destroy();
		        }
	        } catch (Exception e) {
	        	logger.error("IOException", e);
	        }
		}else
			logger.info("无待压缩文件-------------------");
    }

如果需要将linux命令执行时候的输出打印出来,可以将参数StringBuilder sb进行输出即可

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值