001package com.pi4j.util; 002 003/* 004 * #%L 005 * ********************************************************************** 006 * ORGANIZATION : Pi4J 007 * PROJECT : Pi4J :: Java Library (Core) 008 * FILENAME : ExecUtil.java 009 * 010 * This file is part of the Pi4J project. More information about 011 * this project can be found here: https://www.pi4j.com/ 012 * ********************************************************************** 013 * %% 014 * Copyright (C) 2012 - 2021 Pi4J 015 * %% 016 * This program is free software: you can redistribute it and/or modify 017 * it under the terms of the GNU Lesser General Public License as 018 * published by the Free Software Foundation, either version 3 of the 019 * License, or (at your option) any later version. 020 * 021 * This program is distributed in the hope that it will be useful, 022 * but WITHOUT ANY WARRANTY; without even the implied warranty of 023 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 024 * GNU General Lesser Public License for more details. 025 * 026 * You should have received a copy of the GNU General Lesser Public 027 * License along with this program. If not, see 028 * <http://www.gnu.org/licenses/lgpl-3.0.html>. 029 * #L% 030 */ 031 032 033import java.io.BufferedReader; 034import java.io.IOException; 035import java.io.InputStreamReader; 036import java.util.ArrayList; 037import java.util.List; 038 039public class ExecUtil 040{ 041 public static String[] execute(String command) throws IOException, InterruptedException { 042 return execute(command, null); 043 } 044 045 public static String[] execute(String command, String split) throws IOException, InterruptedException { 046 List<String> result = new ArrayList<>(); 047 048 // create external process 049 Process p = Runtime.getRuntime().exec(command); 050 051 // wait for external process to complete 052 p.waitFor(); 053 054 // if the external proess returns an error code (non-zero), then build out and return null 055 if(p.exitValue() != 0) { 056 p.destroy(); 057 return null; 058 } 059 060 // using try-with-resources to ensure closure 061 try(InputStreamReader isr = new InputStreamReader(p.getInputStream()); 062 BufferedReader reader = new BufferedReader(isr)) { 063 // read lines from buffered reader 064 String line = reader.readLine(); 065 while (line != null) { 066 if (!line.isEmpty()) { 067 if (split == null || split.isEmpty()) { 068 result.add(line.trim()); 069 } else { 070 String[] parts = line.trim().split(split); 071 for(String part : parts) { 072 if (part != null && !part.isEmpty()) { 073 result.add(part.trim()); 074 } 075 } 076 } 077 } 078 079 // read next line 080 line = reader.readLine(); 081 } 082 } 083 084 // destroy process 085 p.destroy(); 086 087 // return result 088 if (result.size() > 0) { 089 return result.toArray(new String[result.size()]); 090 } else { 091 return new String[0]; 092 } 093 } 094}