简体   繁体   中英

read inputstream and use if statement to compare output

I want to read a data stream and everytime it reads a certain word or phrase I want the count to go up. The example I have below fails to count it. I tried looking for "echo percent" as well. All the bat file does is echo percent.

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));   

DataInputStream.readLine is deprecated. Use BufferedReader and its readLine method or Scanner and nextLine instead. Also, use .equals to compare two strings, not == .

The == comparison only does a reference comparison, asking the question, "Are these two strings in the same place in memory?" Usually, the answer is "no." On the other hand, equals asks the question, "Are the characters in these two strings the same?" This is called deep comparison, and the == operator doesn't perform the deeper comparison.

Don't compare the Strings with == , use the equals method.

If you compare the Strings with == , you're checking to see if they're the same String .

If you compare them with equals , you're checking whether or not their contents are the same.

Instead of:

if (ls_str == percent)

Do this:

if (ls_str.equals(percent))

If you want to ignore case, you can do it like this:

if (ls_str.equalsIgnoreCase(percent))


EDIT

Your String format is also messed up.

Change:

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

to:

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

Notice the parentheses change.


Take a look at these for more explanations:

Java String.equals versus ==

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM