protected void runScript(String[] cmd, JTextArea txaMsg) { String strg = ""; if (cmd == null) return; Process prcs = null; try { Messages.postDebug("Running script: " + cmd[2]); Runtime rt = Runtime.getRuntime(); prcs = rt.exec(cmd); if (prcs == null) return; InputStream istrm = prcs.getInputStream(); if (istrm == null) return; BufferedReader bfr = new BufferedReader(new InputStreamReader(istrm)); while ((strg = bfr.readLine()) != null) { // System.out.println(strg); strg = strg.trim(); // Messages.postDebug(strg); strg = strg.toLowerCase(); if (txaMsg != null) { txaMsg.append(strg); txaMsg.append("\n"); } } } catch (Exception e) { // e.printStackTrace(); Messages.writeStackTrace(e); Messages.postDebug(e.toString()); } finally { // It is my understanding that these streams are left // open sometimes depending on the garbage collector. // So, close them. try { if (prcs != null) { OutputStream os = prcs.getOutputStream(); if (os != null) os.close(); InputStream is = prcs.getInputStream(); if (is != null) is.close(); is = prcs.getErrorStream(); if (is != null) is.close(); } } catch (Exception ex) { Messages.writeStackTrace(ex); } } }
private Integer startTunnelSSH(Instance instance) throws InterruptedException { Instance tunnelInstance = runningInstances(tunnelResourceId).get(0); Integer localPort = Double.valueOf(Randoms.number(3000, 10000)).intValue(); CountDownLatch latch = new CountDownLatch(1); Thread tunnelThread = new Thread( () -> { Process process = null; try { Path keyPath = KeyPair.keyFile(tunnelInstance.getKeyName(), env); String userAndHost = "ubuntu@" + hostName(tunnelInstance); String portBinding = Strings.format("{}:{}:22", localPort, instance.getPrivateIpAddress()); List<String> command = tunnelCommand(keyPath, userAndHost, portBinding); logger.info("tunnel command => {}", String.join(" ", command)); process = new ProcessBuilder().command(command).start(); process.getInputStream().read(); // wait until there is output latch.countDown(); process.waitFor(); } catch (InterruptedException | IOException e) { throw new IllegalStateException(e); } finally { if (process != null) process.destroy(); } }); tunnelThread.setDaemon(true); tunnelThread.start(); latch.await(); return localPort; }
/** * 压缩文件 * * @param projectId * @param deployFileId * @param filename * @throws IOException */ private void tarFile(Long projectId, Long deployFileId) throws IOException { // 主文件夹 String path = this.fileDeployRoot + "/" + String.valueOf(projectId) + "/deployfile" + String.valueOf(deployFileId) + "/"; // 上传文件名 开头 String fileNameStart = "file" + String.valueOf(deployFileId); // 上传文件名 全名 String fileName = fileNameStart + this.FILE_END_TAGS; // 创建可执行文件,(如果直接执行压缩命令,压缩文件内容为空) String tarFilePath = path + fileNameStart + "/tar.sh"; FileUtils.write(new File(tarFilePath), "tar -zcf " + fileName + " *", false); // 让其有运行的权限 Process p = Runtime.getRuntime().exec("chmod +x " + tarFilePath); while (p.getInputStream().read(new byte[255]) != -1) {} // 执行linux命令,压缩 p = Runtime.getRuntime().exec("./tar.sh", null, new File(path + fileNameStart)); while (p.getInputStream().read(new byte[255]) != -1) {} // 执行linux命令,移到外层文件夹 Runtime.getRuntime().exec("mv " + fileName + " ../", null, new File(path + fileNameStart)); while (p.getInputStream().read(new byte[255]) != -1) {} }
@Before public void setUp() { processManager = new ProcessManager() { @Override Process startProcess(ProcessBuilder processBuilder, String msgCommandInfo) { return processStartedByManager; } }; processStartedByManager = mock(Process.class); when(processStartedByManager.getInputStream()).thenReturn(mock(InputStream.class)); when(processStartedByManager.getErrorStream()).thenReturn(mock(InputStream.class)); when(processStartedByManager.getOutputStream()).thenReturn(mock(OutputStream.class)); processOne = mock(Process.class); processTwo = mock(Process.class); when(processOne.getInputStream()).thenReturn(mock(InputStream.class)); when(processOne.getErrorStream()).thenReturn(mock(InputStream.class)); when(processOne.getOutputStream()).thenReturn(mock(OutputStream.class)); when(processOne.exitValue()).thenThrow(new IllegalStateException()); when(processTwo.exitValue()).thenThrow(new IllegalStateException()); when(processTwo.getInputStream()).thenReturn(mock(InputStream.class)); when(processTwo.getErrorStream()).thenReturn(mock(InputStream.class)); when(processTwo.getOutputStream()).thenReturn(mock(OutputStream.class)); ConcurrentMap<Process, ProcessWrapper> processMap = processManager.getProcessMap(); wrapperForProcessOne = new ProcessWrapper(processOne, "tag1", null, inMemoryConsumer(), null, "ERROR: "); processMap.put(processOne, wrapperForProcessOne); wrapperForProcessTwo = new ProcessWrapper(processTwo, "tag2", null, inMemoryConsumer(), null, "ERROR: "); processMap.put(processTwo, wrapperForProcessTwo); }
private static void checkIsAvailableAndGetVersion() { ProcessBuilder pb = new ProcessBuilder(COMMAND, "--version"); pb.redirectErrorStream(true); Process p = null; try { p = pb.start(); p.waitFor(); perconaToolkitVersion = StreamUtil.getStreamContents(p.getInputStream()); if (perconaToolkitVersion != null) { perconaToolkitVersion = perconaToolkitVersion.replaceAll("\n|\r", ""); } available = true; log.info("Using percona toolkit: " + perconaToolkitVersion); } catch (IOException e) { available = false; } catch (InterruptedException e) { available = false; } finally { if (p != null) { StreamUtil.closeQuietly(p.getErrorStream()); StreamUtil.closeQuietly(p.getInputStream()); StreamUtil.closeQuietly(p.getOutputStream()); p.destroy(); } } }
public static String getArchName() throws Exception { if (archName == null) { archName = "lin"; // bits Process process = Runtime.getRuntime().exec("uname -m"); process.waitFor(); if (process.exitValue() != 0) throw new Exception("Error arch"); BufferedReader inStream = new BufferedReader(new InputStreamReader(process.getInputStream())); String arch = inStream.readLine(); if (arch.equals("i686")) archName += "32"; else archName += "64"; process.destroy(); // SSE process = Runtime.getRuntime().exec("cat /proc/cpuinfo"); process.waitFor(); if (process.exitValue() != 0) throw new Exception("Error /proc/cpuinfo"); inStream = new BufferedReader(new InputStreamReader(process.getInputStream())); String line, cpuinfo = ""; while ((line = inStream.readLine()) != null) cpuinfo += line; String bestSSE = "sse"; String[] sses = {"sse2", "sse3", "ssse3", "sse4", "avx"}; for (int i = 0; i < sses.length; i++) { if (cpuinfo.indexOf(sses[i]) >= 0) bestSSE = sses[i]; } archName += bestSSE; process.destroy(); } return archName; }
public String executeCommand(String command) { System.out.println("$ " + command); StringBuffer output = new StringBuffer(); Process p = null; try { p = execute(command); p.waitFor(); String line = ""; BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((line = reader.readLine()) != null) { output.append(line + "\n"); } reader.close(); reader = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = reader.readLine()) != null) { output.append(line + "\n"); } } catch (Exception e) { e.printStackTrace(); } finally { try { p.getInputStream().close(); p.getOutputStream().close(); p.getErrorStream().close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println(output.toString()); return output.toString(); }
private static JmesPathExpression getAstFromArgument( String argument, Map<String, JmesPathExpression> argumentToAstMap) throws IOException { if (argument != null && !argumentToAstMap.containsKey(argument)) { ProcessBuilder pb = new ProcessBuilder( "/apollo/env/SDETools/bin/brazil-runtime-exec", "python3.4", System.getProperty("codeGenSourceDirectory") + "/bin/jp-to-ast.py", argument); Process p = pb.start(); JsonNode jsonNode = mapper.readTree(IOUtils.toString(p.getInputStream())); JmesPathExpression ast = fromAstJsonToAstJava(jsonNode); argumentToAstMap.put(argument, ast); IOUtils.closeQuietly(p.getInputStream(), null); return ast; } else if (argument != null) { return argumentToAstMap.get(argument); } return null; }
public static void openExternalURL(URL url) throws IOException { if (Util.isWindows()) { // Yes, this only works on windows final String systemBrowser = "explorer.exe"; final Runtime rt = Runtime.getRuntime(); final Process proc = rt.exec( new String[] { systemBrowser, "\"" + url.toString() + "\"", }); new StreamGobbler(proc.getErrorStream()); new StreamGobbler(proc.getInputStream()); } else if (Util.isMacOSX()) { // Yes, this only works on Mac OS X final Runtime rt = Runtime.getRuntime(); final Process proc = rt.exec( new String[] { "/usr/bin/open", url.toString(), }); new StreamGobbler(proc.getErrorStream()); new StreamGobbler(proc.getInputStream()); } else { throw new IOException("Only windows and Mac OS X browsers are yet supported"); } }
/** * Actually executes pt-online-schema change. Does not generate any Sql. * * @return always <code>null</code> */ @Override public Sql[] generate(Database database) { List<String> cmndline = buildCommand(database); log.info("Executing: " + filterCommands(cmndline)); ProcessBuilder pb = new ProcessBuilder(cmndline); pb.redirectErrorStream(true); Process p = null; final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final OutputStream tee = new FilterOutputStream(outputStream) { @Override public void write(int b) throws IOException { if (b == '\n') { log.info(outputStream.toString(Charset.defaultCharset().toString())); outputStream.reset(); } else { super.write(b); } } }; try { p = pb.start(); final InputStream in = p.getInputStream(); final InputStream err = p.getErrorStream(); IOThread reader = new IOThread(in, tee); IOThread reader2 = new IOThread(err, tee); reader.start(); reader2.start(); int exitCode = p.waitFor(); reader.join(5000); reader2.join(5000); // log the remaining output log.info(outputStream.toString(Charset.defaultCharset().toString())); if (exitCode != 0) { throw new RuntimeException("Percona exited with " + exitCode); } } catch (IOException e) { throw new UnexpectedLiquibaseException(e); } catch (InterruptedException e) { throw new UnexpectedLiquibaseException(e); } finally { if (p != null) { StreamUtil.closeQuietly(p.getErrorStream()); StreamUtil.closeQuietly(p.getInputStream()); StreamUtil.closeQuietly(p.getOutputStream()); p.destroy(); } StreamUtil.closeQuietly(outputStream); } return null; }
// 读取cpu相关信息 private static long[] readCpu(final Process proc) { long[] retn = new long[2]; try { proc.getOutputStream().close(); InputStreamReader ir = new InputStreamReader(proc.getInputStream()); LineNumberReader input = new LineNumberReader(ir); String line = input.readLine(); if (line == null || line.length() < FAULTLENGTH) { return null; } int capidx = line.indexOf("Caption"); int cmdidx = line.indexOf("CommandLine"); int rocidx = line.indexOf("ReadOperationCount"); int umtidx = line.indexOf("UserModeTime"); int kmtidx = line.indexOf("KernelModeTime"); int wocidx = line.indexOf("WriteOperationCount"); long idletime = 0; long kneltime = 0; long usertime = 0; while ((line = input.readLine()) != null) { if (line.length() < wocidx) { continue; } // 字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount, // ThreadCount,UserModeTime,WriteOperation String caption = substring(line, capidx, cmdidx - 1).trim(); String cmd = substring(line, cmdidx, kmtidx - 1).trim(); if (cmd.indexOf("wmic.exe") >= 0) { continue; } String s1 = substring(line, kmtidx, rocidx - 1).trim(); String s2 = substring(line, umtidx, wocidx - 1).trim(); if (caption.equals("System Idle Process") || caption.equals("System")) { if (s1.length() > 0) idletime += Long.valueOf(s1).longValue(); if (s2.length() > 0) idletime += Long.valueOf(s2).longValue(); continue; } if (s1.length() > 0) kneltime += Long.valueOf(s1).longValue(); if (s2.length() > 0) usertime += Long.valueOf(s2).longValue(); } retn[0] = idletime; retn[1] = kneltime + usertime; return retn; } catch (Exception ex) { ex.printStackTrace(); } finally { try { proc.getInputStream().close(); } catch (Exception e) { e.printStackTrace(); } } return null; }
/** * Runs a process and waits for it to finish. * * @param processName The name of the process to run. * @param args The arguments to the process. * @throws Exception */ public static void runProcess(String processName, String args) throws Exception { Process p = null; try { p = Runtime.getRuntime().exec(processName + " " + args); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); while (br.readLine() != null) {} } catch (Exception ex) { System.out.println( "An error has occurred while running the process: " + processName + ": " + ex.getMessage()); } finally { if (p != null) { p.waitFor(); // Close input stream try { p.getInputStream().close(); } catch (Exception ex) { System.out.println( "An error has occurred while running the process: " + processName + ": " + ex.getMessage()); } // Close output stream try { p.getOutputStream().close(); } catch (Exception ex) { System.out.println( "An error has occurred while running the process: " + processName + ": " + ex.getMessage()); } // Close error stream try { p.getErrorStream().close(); } catch (Exception ex) { System.out.println( "An error has occurred while running the process: " + processName + ": " + ex.getMessage()); } } } }
@Override protected void startProcessHandler( DBRProgressMonitor monitor, final MySQLDatabaseExportInfo arg, ProcessBuilder processBuilder, Process process) { super.startProcessHandler(monitor, arg, processBuilder, process); String outFileName = GeneralUtils.replaceVariables( outputFilePattern, new GeneralUtils.IVariableResolver() { @Override public String get(String name) { switch (name) { case VARIABLE_DATABASE: return arg.getDatabase().getName(); case VARIABLE_HOST: return arg.getDatabase() .getDataSource() .getContainer() .getConnectionConfiguration() .getHostName(); case VARIABLE_TABLE: final Iterator<MySQLTableBase> iterator = arg.getTables() == null ? null : arg.getTables().iterator(); if (iterator != null && iterator.hasNext()) { return iterator.next().getName(); } else { return "null"; } case VARIABLE_TIMESTAMP: return RuntimeUtils.getCurrentTimeStamp(); default: System.getProperty(name); } return null; } }); File outFile = new File(outputFolder, outFileName); boolean isFiltering = removeDefiner; Thread job = isFiltering ? new DumpFilterJob(monitor, process.getInputStream(), outFile) : new DumpCopierJob( monitor, MySQLMessages.tools_db_export_wizard_monitor_export_db, process.getInputStream(), outFile); job.start(); }
private void runJob(Process p) { InputStream in2 = p.getInputStream(); interpretFromStream(in2); try { p.waitFor(); p.getOutputStream().close(); p.getInputStream().close(); p.getErrorStream().close(); } catch (Throwable e) { System.err.println("I/O Error in Unafold Extension:"); e.printStackTrace(); } }
public ProcessOutput execute( JobConsoleLogger console, boolean showConsoleOutput, String workingDir, List<String> command, Map<String, String> envMap) { ProcessBuilder processBuilder = new ProcessBuilder(command); Process process = null; ProcessOutput processOutput = null; long startTime = System.currentTimeMillis(); try { logger.info(String.format("External process '%s' started", command.get(0))); if (workingDir != null) { processBuilder.directory(new File(workingDir)); } processBuilder.redirectErrorStream(true).environment().putAll(envMap); process = processBuilder.start(); if (showConsoleOutput) { LinesInputStream output = new LinesInputStream(process.getInputStream()); console.readOutputOf(output); int returnCode = process.waitFor(); waitUntilEmpty(2000, output, null); processOutput = new ProcessOutput(returnCode, output.getLines(), new ArrayList<String>()); } else { List output = IOUtils.readLines(process.getInputStream()); int returnCode = process.waitFor(); List pendingOutput = IOUtils.readLines(process.getInputStream()); output.addAll(pendingOutput); processOutput = new ProcessOutput(returnCode, output, new ArrayList<String>()); } } catch (Exception e) { throw new RuntimeException(e.getMessage()); } finally { if (process != null) { closeQuietly(process.getInputStream()); closeQuietly(process.getErrorStream()); closeQuietly(process.getOutputStream()); process.destroy(); long estimatedTime = System.currentTimeMillis() - startTime; logger.info( String.format( "External process '%s' returned %d after %dms.", command.get(0), processOutput.getReturnCode(), estimatedTime)); } } return processOutput; }
/** * Initializes the xml-rpc communication. * * @param port the port where the communication should happen. * @param process this is the process that was spawned (server for the XML-RPC) * @throws MalformedURLException */ public PydevConsoleCommunication(int port, Process process, int clientPort) throws Exception { stdOutReader = new ThreadStreamReader(process.getInputStream()); stdErrReader = new ThreadStreamReader(process.getErrorStream()); stdOutReader.start(); stdErrReader.start(); // start the server that'll handle input requests this.webServer = new WebServer(clientPort); XmlRpcServer serverToHandleRawInput = this.webServer.getXmlRpcServer(); serverToHandleRawInput.setHandlerMapping( new XmlRpcHandlerMapping() { public XmlRpcHandler getHandler(String handlerName) throws XmlRpcNoSuchHandlerException, XmlRpcException { return PydevConsoleCommunication.this; } }); this.webServer.start(); IXmlRpcClient client = new ScriptXmlRpcClient(process, stdErrReader, stdOutReader); client.setPort(port); this.client = client; }
private ProBInstance startProlog() { ProcessHandle processTuple = processProvider.get(); Process process = processTuple.getProcess(); String key = processTuple.getKey(); final BufferedReader stream = new BufferedReader( new InputStreamReader(process.getInputStream(), Charset.defaultCharset())); Map<Class<? extends AbstractCliPattern<?>>, AbstractCliPattern<?>> cliInformation = extractCliInformation(stream); Integer port = ((PortPattern) cliInformation.get(PortPattern.class)).getValue(); Long userInterruptReference = ((InterruptRefPattern) cliInformation.get(InterruptRefPattern.class)).getValue(); ProBConnection connection = new ProBConnection(key, port); try { processCounter.incrementAndGet(); connection.connect(); ProBInstance cli = new ProBInstance( process, stream, userInterruptReference, connection, home, osInfo, processCounter); processes.add(new WeakReference<ProBInstance>(cli)); return cli; } catch (IOException e) { processCounter.decrementAndGet(); logger.error("Error connecting to Prolog binary.", e); return null; } }
private static Architecture getMacOSXArchitecture() { BufferedReader input = null; try { String line; Process proc = Runtime.getRuntime().exec("sysctl hw"); input = new BufferedReader(new InputStreamReader(proc.getInputStream())); while ((line = input.readLine()) != null) { if (line.length() > 0) { if ((line.contains("cpu64bit_capable")) && (line.trim().endsWith("1"))) { return Architecture.x86_64; } } } } catch (Exception e) { throw new OsDetectionException(e); } finally { try { if (input != null) { input.close(); } } catch (Exception ignored) { // ignore } } return Architecture.x86; }
private static Architecture getUnixArchitecture() { BufferedReader input = null; try { String line; Process proc = Runtime.getRuntime().exec("uname -m"); input = new BufferedReader(new InputStreamReader(proc.getInputStream())); while ((line = input.readLine()) != null) { if (line.length() > 0) { if (line.contains("64")) { return Architecture.x86_64; } } } } catch (Exception e) { throw new OsDetectionException(e); } finally { try { if (input != null) { input.close(); } } catch (Exception ignored) { // ignore } } return Architecture.x86; }
public static void main(String[] args) { try { String ls_1; Process process = null; // File handle = new File("../tmp/ctb_v1/data"); File handle = new File("../tmp/ctb_v6/data/bracketed"); BufferedWriter bout = new BufferedWriter( new OutputStreamWriter(new FileOutputStream("../tmp/malt.train"), "UTF-8")); for (File sub : Arrays.asList(handle.listFiles())) { String file = sub.getAbsolutePath(); if (!file.endsWith(".fid")) continue; clean(file); process = Runtime.getRuntime() .exec( "cmd /c java -jar ../tmp/Penn2Malt.jar " + file + " ../tmp/headrules.txt 3 2 chtb"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((ls_1 = bufferedReader.readLine()) != null) { System.out.println(ls_1); } bufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); while ((ls_1 = bufferedReader.readLine()) != null) { System.out.println(ls_1); } } } catch (IOException e) { System.err.println(e); } }
/** * Gets the token. * * @param scope the scope * @return the token */ private String getToken(String scope) { Process curlProc; String outputString; DataInputStream curlIn = null; String access_token = null; String command = "curl -X POST -H Content-Type:application/x-www-form-urlencoded " + adminUrl + "/oauth2/token --insecure --data" + " client_id=" + client_id + "&" + "client_secret=" + client_secret + "&grant_type=client_credentials&scope=" + scope; try { curlProc = Runtime.getRuntime().exec(command); curlIn = new DataInputStream(curlProc.getInputStream()); while ((outputString = curlIn.readLine()) != null) { JSONObject obj = new JSONObject(outputString); access_token = obj.getString("access_token"); } } catch (IOException e1) { e1.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return access_token; }
private void serve(InputStream sis, OutputStream sos) throws IOException { // kills the process if client closes the stream; // closes the stream if process is terminated/ended output. // therefore we need the interruption mechanism. Process process = Runtime.getRuntime().exec("bash"); InputStream pis = process.getInputStream(); InputStream pes = process.getErrorStream(); OutputStream pos = process.getOutputStream(); try { threads.add(new CopyThread(pis, sos)); threads.add(new CopyThread(pes, sos)); threads.add(new CopyThread(sis, pos)); threads.add( new InterruptibleThread() { protected void run0() throws InterruptedException { process.waitFor(); } }); Util.startJoin(threads); } finally { process.destroy(); } }
private void writeLogcat(String name) { CharSequence timestamp = DateFormat.format("yyyyMMdd_kkmmss", System.currentTimeMillis()); String filename = name + "_" + timestamp + ".log"; String[] args = {"logcat", "-v", "time", "-d"}; try { Process process = Runtime.getRuntime().exec(args); InputStreamReader input = new InputStreamReader(process.getInputStream()); OutputStreamWriter output = new OutputStreamWriter(new FileOutputStream(filename)); BufferedReader br = new BufferedReader(input); BufferedWriter bw = new BufferedWriter(output); String line; while ((line = br.readLine()) != null) { bw.write(line); bw.newLine(); } bw.close(); output.close(); br.close(); input.close(); } catch (IOException e) { e.printStackTrace(); } }
/** 读取当前网速 */ public static long getNetSpeed() { ProcessBuilder cmd; long readBytes = 0; BufferedReader rd = null; try { String[] args = {"/system/bin/cat", "/proc/net/dev"}; cmd = new ProcessBuilder(args); Process process = cmd.start(); rd = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; // int linecount = 0; while ((line = rd.readLine()) != null) { // linecount++; if (line.contains("lan0") || line.contains("eth0")) { String[] delim = line.split(":"); if (delim.length >= 2) { readBytes = parserNumber(delim[1].trim()); break; } } } rd.close(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (rd != null) { try { rd.close(); } catch (IOException e) { e.printStackTrace(); } } } return readBytes; }
public static TByteArrayList transformByExternalCommand( final String command, final InputStream input) throws IOException { final Process process = Runtime.getRuntime().exec(command); final InputStream in = process.getInputStream(); final OutputStream out = process.getOutputStream(); final TByteArrayList bytes = new TByteArrayList(100500); final byte[] buffer = new byte[1024 * 1024]; try { int read; while ((read = input.read(buffer)) > 0) { out.write(buffer, 0, read); if (in.available() > 0) { read = in.read(buffer); bytes.add(buffer, 0, read); } } out.close(); while ((read = in.read(buffer)) > 0) { bytes.add(buffer, 0, read); } in.close(); } catch (IOException ioe) { System.err.println(readByteStream(process.getErrorStream())); LOG.error(ioe); throw ioe; } return bytes; }
public String execRecognizer() { try { String inputFile = new File(tmpdir, "input").getAbsolutePath(); String[] args = new String[] {"java", "-classpath", tmpdir + pathSep + CLASSPATH, "Test", inputFile}; // String cmdLine = "java -classpath "+CLASSPATH+pathSep+tmpdir+" Test " + new File(tmpdir, // "input").getAbsolutePath(); // System.out.println("execParser: "+cmdLine); Process process = Runtime.getRuntime().exec(args, null, new File(tmpdir)); StreamVacuum stdoutVacuum = new StreamVacuum(process.getInputStream()); StreamVacuum stderrVacuum = new StreamVacuum(process.getErrorStream()); stdoutVacuum.start(); stderrVacuum.start(); process.waitFor(); stdoutVacuum.join(); stderrVacuum.join(); String output = null; output = stdoutVacuum.toString(); if (stderrVacuum.toString().length() > 0) { this.stderrDuringParse = stderrVacuum.toString(); System.err.println("exec stderrVacuum: " + stderrVacuum); } return output; } catch (Exception e) { System.err.println("can't exec recognizer"); e.printStackTrace(System.err); } return null; }
public static String cpuArch() { if (mCPUArch == null) { /** * Email from [email protected] in 2014/06/27 said their new x86 ROM modifies the * android.os.abi to make the Build.CPU_ABI to always return "armeabi-v7a" and recommended * following method to get real CPU arch. */ BufferedReader ibr = null; try { Process process = Runtime.getRuntime().exec("getprop ro.product.cpu.abi"); ibr = new BufferedReader(new InputStreamReader(process.getInputStream())); mCPUArch = ibr.readLine(); } catch (IOException e) { } finally { if (ibr != null) { try { ibr.close(); } catch (IOException e) { } } } if (TextUtils.isEmpty(mCPUArch)) { // if meet something wrong, get cpu arch from android sdk. mCPUArch = Build.CPU_ABI; } } return mCPUArch; }
/** * Execute the given command and optionally wait and dump the results to standard out * * @param args command and arguments * @param wait true =wait for either completion or timeout time and dump output, false don't wait * and ignore the output. * @exception Exception */ private static void execCmdDumpResults(String[] args, boolean wait) throws Exception { // We need the process inputstream and errorstream ProcessStreamResult prout = null; ProcessStreamResult prerr = null; System.out.flush(); bos.flush(); BufferedOutputStream _bos = bos; if (!wait) { // not interested in the output, don't expect a huge amount. // information will just be written to the byte array in // memory and never used. _bos = new BufferedOutputStream(new ByteArrayOutputStream()); } // Start a process to run the command Process pr = execCmd(args); // Note, the timeout handling will only come into effect when we make // the Wait() call on ProcessStreamResult. prout = new ProcessStreamResult(pr.getInputStream(), _bos, timeoutMinutes); prerr = new ProcessStreamResult(pr.getErrorStream(), _bos, timeoutMinutes); if (!wait) return; // wait until all the results have been processed or if we timed out prout.Wait(); prerr.Wait(); _bos.flush(); System.out.flush(); }
/** this void method runs the command created in the constructor. */ public void runTesseract() { LOGGER.info( "Trying to run command: " + command[0] + " " + command[1] + " " + command[2] + " " + command[3] + " " + command[4]); System.out.println("Trying to run command: " + Arrays.toString(command)); try { Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(command); BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line; while ((line = input.readLine()) != null) { System.out.println(line); } int exitVal = pr.waitFor(); System.out.println("Exited with error code " + exitVal); } catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); } }
public static String getSDCardPath() { String cmd = "cat /proc/mounts"; Runtime run = Runtime.getRuntime(); // 返回与当前 Java 应用程序相关的运行时对象 try { Process p = run.exec(cmd); // 启动另一个进程来执行命令 BufferedInputStream in = new BufferedInputStream(p.getInputStream()); BufferedReader inBr = new BufferedReader(new InputStreamReader(in)); String lineStr; while ((lineStr = inBr.readLine()) != null) { // 获得命令执行后在控制台的输出信息 // Log.i("CommonUtil:getSDCardPath", lineStr); if (lineStr.contains("sdcard") && lineStr.contains(".android_secure")) { String[] strArray = lineStr.split(" "); if (strArray != null && strArray.length >= 5) { String result = strArray[1].replace("/.android_secure", ""); return result; } } // 检查命令是否执行失败。 if (p.waitFor() != 0 && p.exitValue() == 1) { // p.exitValue()==0表示正常结束,1:非正常结束 Log.e("CommonUtil:getSDCardPath", "命令执行失败!"); } } inBr.close(); in.close(); } catch (Exception e) { // Log.e("CommonUtil:getSDCardPath", e.toString()); return Environment.getExternalStorageDirectory().getPath(); } return Environment.getExternalStorageDirectory().getPath(); }