0

Am trying to find the character count between = and \n new line character using below java code. But \n is not considering in my case.

am using import org.apache.commons.lang3.StringUtils; package

Please find my below java code.

public class CharCountInLine {
    
     public static void main(String[] args) 
        {
    
     BufferedReader reader = null;
 
     try
     {
                  
         reader = new BufferedReader(new FileReader("C:\\wordcount\\sample.txt"));
          
                 
         String currentLine = reader.readLine();
         
         String[] line = currentLine.split("=");

         
         while (currentLine != null ){
             String res = StringUtils.substringBetween(currentLine, "=", "\n"); //    \n is not working.
             if(res != null) {
             System.out.println("line -->"+res.length());
             }
             currentLine = reader.readLine();
         }
         
      } 
     catch (IOException e) 
     {
         e.printStackTrace();
     }
     finally
     {
         try
         {
             reader.close();        
         }
         catch (IOException e) 
         {
             e.printStackTrace();
         }
     }
 }

}

Please find my sample text file.

sample.txt

Karthikeyan=123456
sathis= 23546
Arun = 23564
Karthikeyan
  • 1,927
  • 6
  • 44
  • 109
  • Does this answer your question? [How to split a string in Java](https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – Abhijit Sarkar Mar 10 '21 at 07:44
  • 2
    If your keys are unique, you could probably get away with treating it like a [Java properties file](https://docs.oracle.com/javase/tutorial/essential/environment/properties.html). No need to parse it yourself then. – Robby Cornelissen Mar 10 '21 at 07:46

2 Answers2

4

Well, you're reading the string using readLine(), which according to the Javadoc (emphasis mine):

Returns:

A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

So your code doesn't work because the string does not contain a newline character.


You can address this in a number of ways:

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
-2

You don't need to change how you read the lines, simply change your logic to extract the text after =.

Pattern p = Pattern.compile("(?:.+)=(.+)$");
Matcher m = p.matcher("Karthikeyan=123456");
if (m.find()) {
    System.out.println(m.group(1).length());
}

No need for Apache StringUtils either, simple Java regex will do. If you don't want to count whitespace, trim the string before calling length().

Alternatively, you can also split the line around = as discussed here.

10x simpler code:

Path p = Paths.get("C:\\wordcount\\sample.txt");
Files.lines(p)
  .forEach { line ->
    // Put the above code here
}
Abhijit Sarkar
  • 21,927
  • 20
  • 110
  • 219