简体   繁体   中英

String comparison not breaking out of a while loop

I am trying these lines:

private String line;
private final String stopChr= "#";

BufferedReader in  = new BufferedReader(new InputStreamReader(server.getInputStream()));

while ((line = in.readLine()) != null) {
        tcpData = tcpData + line;
        if(line.equals(stopChr)) break;
}

Why is the if statement not breaking out of the loop when # is present?

Most likely the line is not exactly "#" for example it might have a space after it. I suggest you look at what the line is in your debugger or in an editor to see exactly what characters the String has.

Try printing the following to help see what the string is actually.

System.out.println(Arrays.toString(line.toCharArray());

If you have trailing spaces you can drop these with trim

if (line.trim().equals(stopChar)) break;

If the string contains other characters, as in your example input $353323058181636,EV,D,T,567888.9,+12C,FFFFE000# (from your comment on @PeterLawrey's answer), use the following instead of String.equals :

if(line.contains(stopChr)) break;

If it specifically ends with the stop character, you can alternatively use:

if(line.endsWith(stopChr)) break;

The following code is working :

 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = "";
        String data = "";
        while ((line = br.readLine()) != null) {
            data += line;
            if (line.contains("#"))
                break;
        }

Also, instead of contains() you can use endsWith() to check for end of file. You make take help.

for getting everything before the #

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String line = "";
    String data = "";
    while (true)
        {
        line = br.readLine();

        // break if terminated
        if (line==null)
            break;

        // Check : for debugging only
        System.err.println("LINE : "+line);

        // break if #
        if (line.contains("#"))
            {
            // Get first part, part after, we dont care
            int first=line.indexOf('#');
            data+=line.substring(0, first);

            break;
            }

        else
        data += line;

    }
    // See the result
    System.out.println("DATA:"+data);

The problem solved. readLine() function need end of string character <CR> . Just replacing "#" to "\\n" solved the problem. Thanks to all great team.

you will never get null if the inputstream is from socket. Instead, the readLine() method will block until you get new data.

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