2021SC@SDUSC
目录
项目名称:multimedia-utils
博客十一
在上篇博客我们介绍的是json文件。主要讲的在这个项目里,为了我们更方便的储存临时数据和对数据进行提取,我们用json文件对相应的的数据进行提取。在下面我们将介绍runtimeutils。
RuntimeUtils
在每一个java进程之中都会存在有一个Runtime类的对象。由于此类的对象是由Java进程自己维护,所以在整个Runtime类设计的过程之中,只为用户提供了唯一的一个实例化对象。所以这个类所使用的就是单例设计模式,构造方法被私有化了。所以其类的内部一定会提供有一个static方法取得本类的实例化对象。
取得Runtime类对象:public static Runtime getRuntime()
那么取得对象之后可以做什么呢?在Runtime类中定义有如下可以取得内存大小的方法。
最大可用内存大小:public long maxMemory()
总共可用内存大小:public long totalMemory()
空闲内存大小:public long freeMemory()
下面我们来给出相关代码段。
package com.whty.zdxt.multimedia.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* @author GuoNanLin
* @date 2020-10-30
*/
class RuntimeUtils {
private static final Log log = LogFactory.getLog(RuntimeUtils.class);
/**
* 执行cmd命令,打印成功失败信息
*/
public static void execSF(String command) {
log.debug("执行命令:" + command);
Process exec = null;
try {
exec = Runtime.getRuntime().exec(command);
exec.waitFor();
RuntimeUtils.successful(exec);
String failure = RuntimeUtils.failure(exec);
int i = exec.exitValue();
if (i != 0) {
throw new RuntimeException(failure);
}
} catch (IOException | InterruptedException e) {
throw new RuntimeException("执行命令失败", e);
} finally {
if (exec != null) {
exec.destroy();
}
}
}
/**
* 执行cmd命令,打印失败信息
*/
public static void execFailure(String command) {
log.debug("执行命令:" + command);
Process exec = null;
try {
exec = Runtime.getRuntime().exec(command);
exec.waitFor();
String failure = RuntimeUtils.failure(exec);
int i = exec.exitValue();
if (i != 0) {
throw new RuntimeException(failure);
}
} catch (IOException | InterruptedException e) {
throw new RuntimeException("执行命令失败", e);
} finally {
if (exec != null) {
exec.destroy();
}
}
}
/**
* 执行cmd命令,打印失败信息
*/
public static String execSuccessful(String command) {
log.debug("执行命令:" + command);
Process exec = null;
String response = null;
try {
exec = Runtime.getRuntime().exec(command);
response = RuntimeUtils.successful(exec);
} catch (IOException e) {
throw new RuntimeException("执行命令失败", e);
} finally {
if (exec != null) {
exec.destroy();
}
}
return response;
}
/**
* 获取执行成功结果
*/
private static String successful(Process exec) throws IOException {
InputStream is = exec.getInputStream();
return response(is);
}
/**
* 获取执行失败结果
*/
private static String failure(Process exec) throws IOException {
InputStream is = exec.getErrorStream();
return response(is);
}
/**
* 打印执行结果
*
* @param is 结果输入流
*/
private static String response(InputStream is) throws IOException {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
String r = "";
while ((line = br.readLine()) != null) {
// System.out.println(line);
r = r + line;
}
return r;
}
}