首页 > 解决方案 > 用Java格式化数据并输入到数据库

问题描述

我正在使用 java 中的进程构建器从 cmd 获取硬件数据。

//get info from cmd
    ProcessBuilder processBuilder = new ProcessBuilder();

        processBuilder.command("cmd.exe", "/c", "systeminfo ");

        try {

            Process process = processBuilder.start();

            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(process.getInputStream()));
            //write the output to the variables
            String line;
            //a loop which ensures all the data is read in
            while ((line = reader.readLine()) != null) {
                hardwareInfo.add(line);//hardwareInfo is an arraylist i currently save all this information to
            }

这将返回所有相关信息和更多信息。我的输出如下所示:

[, Host Name:                 LJDESKTOP, OS Name:                   Microsoft Windows 10 Education, OS Version:                10.0.18363 N/A Build 18363

ETC...

我想根据它们的名称将其中一些字段添加到 SQL 数据库中(例如主机名:-是,操作系统名称:-否)。SQL 连接已建立,我只需要找到保存这些变量的最佳方法,这样我就可以将它们直接插入到我的数据库中。

那么我如何摆脱Host Name:并仍然进入LJDESKTOP我的数据库以及我从 cmd 命令获得的其余信息的相同原则。

我也在尝试考虑效率,我希望这在计算上尽可能“轻”,但这不是必需的。

到目前为止我已经尝试过:

  1. 我尝试在“:”处为每个变量和修剪分割字符串。这为我提供了我需要的确切信息,但我无法将其保存到单个变量中。这是因为我修剪的部分是我确定我的变量是什么的方式。(我可以将修剪功能添加到我的二传手吗?)

  2. 我努力了:

    while ((line = reader.readLine()) != null) {

        if (line.startsWith("Host Name:")) {
            setHostname(line.replaceFirst("Host Name: ", ""));}
    

对每个变量重复 if 语句,但是每次通过 while 循环时,这会将每个变量添加到我的数组中。

标签: javasqlcmdprocessbuilderdataformat

解决方案


你可以这样尝试:

...
final Map<String,String> inputValues = new HashMap<>();

//a loop which ensures all the data is read in
while ((line = reader.readLine()) != null) {
  // Read each line as key and value into a the inputValues map

  final String[] pieces = line.split(":",2); // only split at the first ':'!

  // Was a ':' found, e.g. the string split into two pieces?
  if ( pieces.length > 1 ) {

    String key = pieces[0]; // e.g. "Host Name"
    String value = pieces[1]; // e.g. "                 LJDESKTOP"

    value = value.trim(); // remove leading/trailing whitespaces from value

    inputValues.put(key,value); // Store key+value to map.
  }
}

// Now we can access the input values by key, e.g.:

String hostName = inputValues.get("Host Name");
String osName = inputValues.get("OS Name");

// To do: Do something with the values above, e.g. send to DB...

推荐阅读