package com.moke.util;
import java.io.*;
import java.util.Properties;
public class ProjectUtils {
/**
* 用于修改原来树莓派上的信息
*
* @param oldStr
* @param newStr
* @return
* @throws Exception
*/
public synchronized static String repalce(String oldStr, String newStr) throws Exception {
String temp = "";
String result = "";
String path = "";
path = "/etc/dhcpcd.conf";
//上面注释的路径是树莓派中的路径,大家根据实际情况进行补充自己系统所处文件的位置
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
// 保存该行前面的内容
for (int j = 1; (temp = br.readLine()) != null && !(temp.split("=")[0].toString()).equals(oldStr); j++) {
buf = buf.append(temp);
buf = buf.append(System.getProperty("line.separator"));
}
/**
* 当所写行的=前面的内容与oldStr相同时,修改本行中的内容 修改后的值为temp1
*/
String temp1 = temp.replaceAll(temp.split("=")[1].toString(), "" + newStr);
buf = buf.append(temp1);
// 保存该行后面的内容
while ((temp = br.readLine()) != null) {
buf = buf.append(System.getProperty("line.separator"));
buf = buf.append(temp);
}
br.close();
FileOutputStream fos = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
pw.close();
return "success";
}
/**
* 用与前端页面进行回显信息
*
* @param filePath
* @param key
* @return
* @throws Exception
*/
public static String readData(String filePath, String key) throws Exception {
filePath = "/etc/dhcpcd.conf";
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = br.readLine()) != null) { // 一次读取一行
String[] tmp = line.split("="); // 根据=将每行数据拆分成一个数组
for (int i = 0; i < tmp.length; i++) {
if (key.equals(tmp[0].toString())) {
return tmp[1];// tmp[1]就是你想要的bb
}
if (key.equals(tmp[0].toString())) {
return tmp[1];
}
if (key.equals(tmp[0].toString())) {
return tmp[1];
}
}
}
br.close();
return null;
}
/**
* 用于对树莓派系统进行命令操作(重启网卡,或者重启系统等)
*
* @param cmd
* @return
*/
public static String executeLinuxCmd(String cmd) {
System.out.println("got cmd job : " + cmd);
Runtime run = Runtime.getRuntime();
try {
Process process = run.exec(cmd);
InputStream in = process.getInputStream();
BufferedReader bs = new BufferedReader(new InputStreamReader(in));
// System.out.println("[check] now size \n"+bs.readLine());
StringBuffer out = new StringBuffer();
byte[] b = new byte[8192];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
System.out.println("job result [" + out.toString() + "]");
in.close();
// process.waitFor();
process.destroy();
return out.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}