使用Java replace()

时间:2018-05-17 16:46:42

标签: java string unicode replace wmic

我目前正在开发系统配置检查程序。为此,我需要检索被测试机器的操作系统并根据.csv文件对其进行测试。

不幸的是,在测试时,一台机器让我非常头疼:从WMI命令中检索字符串后,会插入一个ÿ个字符。结果,我的字符串比较是错误的,实际上它不应该。这是一个小代码块,可帮助您了解该过程:

    //The command to execute
    String masterCommand = "wmic os get ";
    String command = "Caption";

    //The process that executes the command
    ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", masterCommand + command);
    Process p = pb.start();
    p.waitFor();
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    //The command result stored in a string
    while((line = br.readLine()) != null) {
        result += line;
    }
    //The string cleaned of unwanted substring and trailing spaces
    result = result.replace(command, "").trim();

预期结果为Microsoft Windows 10 Enterprise,但最终为Microsoft Windowsÿ10 Enterprise

我认为使用Java的replace()方法可以解决问题,但它什么都不做。这是我目前使用的替代品。

    result = result.replace("(?i)windows.", "Windows ");

我应该补充说,命令(wmic os get Caption)在cmd上输出正确的结果,并且似乎也正确地将其输出到.txt文件。

TL; DR

我使用ProcessBuilder在Java中使用wmic,并获得ÿ未检测到的不需要的字符(replace())。

我能做些什么来获得正确的结果(避免写入文件然后阅读)?

请指出任何澄清或纠正的必要。

提前感谢您的回答。

2 个答案:

答案 0 :(得分:0)

你试过这个吗?

     String result = "Microsoft Windowsÿ10 Enterprise";
     result = result.replace('ÿ', ' ');
     System.out.println(result); //prints Microsoft Windows 10 Enterprise

答案 1 :(得分:0)

我找到了一个有点笨重的解决方案但对我有用。

因为不需要的字符是Unicode字符,所以我只是通过保留ASCII字符来清理字符串。

result = result.replaceAll("[^ -~]", "").trim().replaceAll(" +", " ");
result = result.replace("(?i)windows[^ ]", "Windows ");

这样做是需要result字符串并且无需替换(""空字符串)所有字符,其值超出(空格)到{{1} } range(printable ASCII)。

附加代码只修剪所有空格,并用一个空格替换2个以上的空格。 最后一行负责处理" Windows"之间的潜在可打印ASCII字符。及其版本(例如7,XP,Vista等)。