格式化数据并在java中输入到数据库

vjrehmav  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(340)

关闭。这个问题需要更加突出重点。它目前不接受答案。
**想改进这个问题吗?**通过编辑这篇文章更新这个问题,使它只关注一个问题。

18天前关门了。
改进这个问题
我使用java中的processbuilder从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。
我也试图考虑效率,我希望这是尽可能计算“轻”,但这不是必要的。
到目前为止,我尝试了:
我尝试过在“:”处为每个变量拆分字符串并进行修剪。这给了我确切的信息,我需要的,但我不能保存到个别变量。这是因为我修剪的位是如何确定变量的(我是否可以在setter中添加trim函数?)
我试过:
while((line=reader.readline())!=(空){

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

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

pu82cl6c

pu82cl6c1#

您可以这样尝试:

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

相关问题