1

How can I delete a few characters from a file by giving their position? Is there a function to do this?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

No. Copy the rest of the file out to another file, remove the old file, and rename the new file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.