1

Current Output looks like : { "1": "abc", "2": "def", "3": "ghi", }

Expected : { "1": "abc", "2": "def", "3": "ghi" } // No last comma

CODE :

BufferedReader br = new BufferedReader(reader);
String nextLine = ""; 
StringBuilder sb = new StringBuilder();
sb.append("{ \n");
while ((nextLine = br.readLine()) != null) {
    sb.append(...);
    sb.append(",");
    sb.append("\n");
}
sb.append("}");
devk
  • 21
  • 1
  • 9

5 Answers5

7

You can simply do like -

String nextLine = ""; 
StringBuilder sb = new StringBuilder();
sb.append("{ \n");
while ((nextLine = br.readLine()) != null) {
    sb.append(...);
    sb.append(",");
    sb.append("\n");
}
sb.deleteCharAt(sb.lastIndexOf(","));    //You can check here if string builder has comma to avoid IndexOutofboundException
sb.append("}");
Mr Roshan Pawar
  • 5,267
  • 4
  • 28
  • 44
3

You can use deleteCharAt method

StringBuilder strbuilder = new StringBuilder();
strbuilder.append(" { \"1\": \"abc\", \"2\": \"def\", \"3\": \"ghi\",}");

strbuilder.deleteCharAt(strbuilder.length()-(strbuilder.length()-strbuilder.lastIndexOf(",")));
System.out.println(strbuilder.toString());

This will give the following output

 { "1": "abc", "2": "def", "3": "ghi"}
3

Ninad's answer is good if you know the length of your input, but in your case you are reading in a loop and may not have that answer beforehand.

In that case, instead of putting a comma after each readline and then handling the odd end-case, you could put the comma before each readline and handle the known start-case.

String nextLine = ""; 
StringBuilder sb = new StringBuilder();
sb.append("{\n");
nextLine = br.readLine();
sb.append(...);
while ((nextLine = br.readLine()) != null) {
  sb.append(",\n");
  sb.append(...);
}
sb.append("\n}\n");
mbrandeis
  • 130
  • 2
1

Please note this is not a best solution , but will work with minimal changes in your code

So to avoid last comma, you can add if condition. When it comes to last index do not add the comma.

Run the loop first to get total count.

int lineCount=0;
while ((nextLine = br.readLine()) != null) {
 lineCount++;
}

After that again run the loop (your existing code with if condition)

int lineNumber=0;
while ((nextLine = br.readLine()) != null) {
    sb.append(...);

    if(lineNumber<lineCount){  // if current line is less that total count      
                               // then only attach comma
      sb.append(",");
    }

    sb.append("\n");
    lineNumber++;
}
Ninad Pingale
  • 5,634
  • 4
  • 24
  • 45
1

More Dynamic option

       StringBuilder str = new StringBuilder("Test,");
       System.out.println("length = " + str.replace(str.length()-1, str.length(), ""));

Always good to null check before you do replace.

For your specific case

StringBuilder str = new StringBuilder("{"1": "abc", "2": "def", "3": "ghi",}");
System.out.println("length = " + str.replace(str.length()-2, str.length()-1, ""));
bobs_007
  • 158
  • 9