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