问题背景LinuxUtils工具类Lyric:梦想挟带眼泪
问题背景有时候会操作linux指令读取或修改文件,封装一个常用的Linux工具类比较方便
LinuxUtils工具类1 LinuxUtils工具类
package com.yg.util;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
@Slf4j
public class LinuxUtils {
public static boolean downloadHdfsFile(String hdfsPath, String outputPath) {
String cmd = "hdfs dfs -cat " + hdfsPath + "
public static String getCmdResult(String cmd) {
String result = "";
try {
Process process = Runtime.getRuntime().exec(cmd);
InputStreamReader ir = new InputStreamReader(process.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line;
while ((line = input.readLine()) != null) {
result = line;
}
} catch (IOException e) {
System.err.println("IOException " + e.getMessage());
}
return result;
}
public static String getGrepCmdReturn(String cmdStr) {
String[] cmd = new String[3];
cmd[0] = "/bin/sh";
cmd[1] = "-c";
cmd[2] = cmdStr;
//得到Java进程的相关Runtime运行对象
Runtime runtime = Runtime.getRuntime();
StringBuffer stringBuffer = null;
try {
Process process = runtime.exec(cmd);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
stringBuffer = new StringBuffer();
String temp = null;
while ((temp = bufferReader.readLine()) != null) {
stringBuffer.append(temp);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuffer.toString();
}
public static int getFileRows(String path) {
FileReader in;
int rows = 0;
try {
in = new FileReader(path);
LineNumberReader reader = new LineNumberReader(in);
reader.skip(Long.MAX_VALUE);
rows = reader.getLineNumber();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return rows;
}
public static void main(String[] args) {
System.out.println(LinuxCmdUtils.getGrepCmdReturn("dmidecode -s system-serial-number|grep -v "#""));
}
}
作为程序员第 80 篇文章,每次写一句歌词记录一下,看看人生有几首歌的时间,wahahaha …



