0

データ ストリームを読み取りたいのですが、特定の単語やフレーズを読み取るたびにカウントを増やしたいと考えています。以下の例では、それを数えることができません。「エコーパーセント」も探してみました。バッチ ファイルが行うのは、エコー パーセントだけです。

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メソッドまたはScannerand をnextLine代わりに使用します。また、.equalsではなく、2 つの文字列を比較するために使用し==ます。

比較は==参照比較のみを行い、「これら 2 つの文字列はメモリ内の同じ場所にありますか?」という質問をします。通常、答えは「いいえ」です。一方、equalsは「この 2 つの文字列の文字は同じですか?」という質問をします。これは深い比較と呼ばれ、==演算子はより深い比較を実行しません。

于 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 に答える