How can I delete a few characters from a file by giving their position? Is there a function to do this?
2 Answers
You could do this
/**
* Replaces the caracter at the {@code index} position with the {@code newChar}
* character
* @param f file to modify
* @param index of the character to replace
* @param newChar new character
* @throws FileNotFoundException if file does not exist
* @throws IOException if something bad happens
*/
private static void replaceChar(File f, int index, char newChar)
throws FileNotFoundException, IOException {
int fileLength = (int) f.length();
if (index < 0 || index > fileLength - 1) {
throw new IllegalArgumentException("Invalid index " + index);
}
byte[] bt = new byte[(int) fileLength];
FileInputStream fis = new FileInputStream(f);
fis.read(bt);
StringBuffer sb = new StringBuffer(new String(bt));
sb.setCharAt(index, newChar);
FileOutputStream fos = new FileOutputStream(f);
fos.write(sb.toString().getBytes());
fos.close();
}
But notice it will not work for very large files as f.length() is casted to int. For those you should use the usual approach of reading the whole file and dumping it on another one.