0

Im trying to remove all commas at the end of line in a text file but keep the rest of the commas. It can have 0,1,2 or 3 commas at the end.

here is my code but its throwing index out of range -1 exception. I don't understand why since I only remove the commas at the end. I also tried with regex but its not working.

EDIT: turns out I had a line with only a comma at end of one of the files. thats why it was giving the exception only on that file and it was working on the others. stupid mistake.. please delete the question if you think its unnecessary.

 BufferedReader reader = null;
    Writer writer = null;
    try { 
        reader = new BufferedReader(
                new InputStreamReader(
                        new FileInputStream(
                                "C:\\Users\\admin\\Desktop\\test.txt"))); //INPUT FILE

        writer = new BufferedWriter(new FileWriter(
                "C:\\Users\\admin\\Desktop\\fixedlist.txt"));
        String line = null;
        while ((line = reader.readLine()) != null) {
            //line.replaceAll(" ,$", ""); //tried this regex with no luck
            while (line.endsWith(",")){
                    line = line.substring(0, line.length()-1);
            }

            String line1 = line.substring(0, line.indexOf(",")); //throws StringIndexOutOfBoundsException: String index out of range: -1
            String line2 = line.substring(line.indexOf(",") + 1,
                    line.length());
               //surround line1 and line2 with double quotes and write into file
            writer.write("\"" + line1 + "\"" + "," + "\"" + line2 + "\""
                    + "\n");
nailoxx
  • 9
  • 6
  • notice that String#replaceAll doesn't replace in place meaning you need to do line = line.replaceAll(someRegex, ""); – user2717954 Nov 15 '14 at 17:58
  • and the reason the line String line1 = line.substring(0, line.indexOf(",")); throws an exception is that the line has no comma in it and so indexOf returns -1 – user2717954 Nov 15 '14 at 18:00

1 Answers1

0

You can use Apache commons library, org.apache.commons.lang.StringUtils Then you can use as follows.

String line1 = StringUtils.stripEnd(line, ',')   // strip chars end of the string
String line1 = StringUtils.stripStart(line, ',')   // strip chars start of the string
elixir
  • 1,394
  • 1
  • 11
  • 21