有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

sql格式化数据并在Java中输入数据库

我使用java中的process builder从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

等等

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

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

<>我也试图考虑效率,我希望这是尽可能的计算“光”,但这不是必要的。

到目前为止我所尝试的:

  1. 我尝试过在“:”处为每个变量和修剪拆分字符串。这正好提供了我需要的信息,但我无法将其保存到单个变量中。这是因为我修剪的部分是如何确定变量的。(我是否可以将微调功能添加到我的设定器中?)

  2. 我试过:

    而((line=reader.readLine())!=空){

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

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


共 (1) 个答案

  1. # 1 楼答案

    您可以这样尝试:

    ...
    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...