如何通过指定位置从文件中删除几个字符?是否有执行此操作的功能?
最佳答案
你可以这样做
/**
* 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/