samedi 15 novembre 2014

Need to remove multiple commas at end of line in java


Vote count:

0




Im trying to remove all commas at the end of line in a text file. 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.



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());
writer.write("\"" + line1 + "\"" + "," + "\"" + line2 + "\""
+ "\n");


asked 50 secs ago







Need to remove multiple commas at end of line in java

Aucun commentaire:

Enregistrer un commentaire