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("}");
14
  • 2
    how was the output generated? Commented May 29, 2015 at 5:44
  • @leon : I am appending the comma after each line, so looks like { "1": "abc", "2": "def", "3": "ghi", } instead I want to ignore the last comma before appending. Commented May 29, 2015 at 5:45
  • What is the difference between expected and current output? Commented May 29, 2015 at 5:46
  • Post you code... you will get a much better response rate Commented May 29, 2015 at 5:46
  • 1
    possible duplicate of Remove last character of a StringBuilder? Commented May 29, 2015 at 5:57

5 Answers 5

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

//avoid IndexOutOfBoundsException
int lastIndexOfComma = sb.lastIndexOf(",");
if (lastIndexOfComma != -1)
   sb.deleteCharAt(lastIndexOfComma);
sb.append("}");
Sign up to request clarification or add additional context in comments.

2 Comments

This worked for me at the moment! Thanks :) @MrSuS
Alternatively see this answer: stackoverflow.com/a/41282608/363573
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 Comments

This works, but building a string just to delete a section later seems very inneficient
@Leon I agree with your point, this was answered before he post the code. I would chose mbrandeis answer, but that needs a null check and some tweaks
A solution without deleteCharAt: stackoverflow.com/a/41282608/363573
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");

1 Comment

What if the first br.readLine() returns null?
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, ""));

Comments

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++;
}

3 Comments

how does this work? could you please brief?
In you question - br.readLine() - what is br ?
oops, forgot to mention, its an object of BufferedReader -> BufferedReader br = new BufferedReader(new FileReader(fileName));

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.