0

我想读取一个数据流,每次它读取某个单词或短语时,我都希望计数增加。我在下面的示例无法计算它。我也尝试寻找“回声百分比”。bat 文件所做的只是回显百分比。

try { 
    String ls_str;
    String percent = "percent";
    Process ls_proc = Runtime.getRuntime().exec("c:\\temp\\percenttest.bat"); 
    // get its output (your input) stream    
    DataInputStream ls_in = new DataInputStream(ls_proc.getInputStream()); 
    while ((ls_str = ls_in.readLine()) != null ) { 
        System.out.println(ls_str);
        progressBar.setValue(progress);
        taskOutput.append(String.format(ls_str+"\n", progress));
        if (ls_str == percent)  {
            progress++;   
        } 
    }
} catch (IOException e1) { 
    System.out.println(e1.toString());                 
    e1.printStackTrace();
}

setProgress(Math.min(progress, 100));   
4

2 回答 2

1

DataInputStream.readLine已弃用。使用BufferedReader和它的readLine方法或ScannernextLine代替。此外,用于.equals比较两个字符串,而不是==.

比较==只做一个参考比较,问一个问题,“这两个字符串在内存中的同一个地方吗?” 通常,答案是“不”。另一方面,equals问问题:“这两个字符串中的字符是否相同?” 这称为深度比较,==运算符不执行深度比较。

于 2012-09-05T15:15:38.897 回答
0

不要将字符串与 进行比较==,请使用该equals方法。

如果您将字符串与 进行比较==,您正在检查它们是否相同String

如果将它们与 进行比较equals,您正在检查它们的内容是否相同。

代替:

if (ls_str == percent)

做这个:

if (ls_str.equals(percent))

如果你想忽略大小写,你可以这样做:

if (ls_str.equalsIgnoreCase(percent))


编辑

你的字符串格式也搞砸了。

改变:

taskOutput.append(String.format( ls_str+"\n", progress));

到:

taskOutput.append(String.format( ls_str+"\n"), progress);

注意括号的变化。


看看这些以获得更多解释:

Java String.equals 与 ==

http://www.java-samples.com/showtutorial.php?tutorialid=221

于 2012-09-05T15:10:30.977 回答