如何从Java中删除文件中的字符?

时间:2010-02-10 10:29:34

标签: java

如何通过提供位置从文件中删除一些字符?有没有这样做的功能?

2 个答案:

答案 0 :(得分:2)

你可以这样做

/**
 * 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();
}

但请注意,它不适用于非常大的文件,因为f.length()被转换为int。对于那些你应该使用通常的方法来读取整个文件并将其转储到另一个文件。

答案 1 :(得分:1)

没有。将文件的其余部分复制到另一个文件,删除旧文件,然后重命名新文件。