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进行输出即可

你可能感兴趣的:(java)