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

标签 java

如何通过指定位置从文件中删除几个字符?是否有执行此操作的功能?

最佳答案

你可以这样做

/**
 * 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。对于那些您应该使用读取整个文件并将其转储到另一个文件的常用方法。

关于java - 如何从 Java 文件中删除字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2236027/

相关文章:

Java:结合使用 BufferedReader 和 PrintWriter 会导致问题

java - 继承方法和公共(public)方法有什么区别?

java - 在 Serializable Java 类中使用 Logger 的正确方法是什么?

java - 无法在 Fedora 14 上安装 JDK 1.7

java - 从 Maven 迁移到 SBT

java - 无法从 InputStream 读取多个可外部化对象

java - 如何使用 java8 在字符串中查找第一个重复和不重复的字符

java - Eclipse 控制台窗口中的间歇性错误消息

java - 如何基于带注释的参数编写方面切入点

javax.security.sasl.SaslException : Authentic Failed while connecting to Jboss 7 server from remote client