如何在Java中删除文件中的字符?
如何通过给出字符的位置来删除文件中的几个字符?是否有执行此操作的功能?否。将文件的其余部分复制到另一个文件,删除旧文件,然后重命名新文件。您可以执行此操作如何在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 * @
/**
* 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();
}
/**
*将{@code index}位置的字符替换为{@code newChar}
*性格
*@param f要修改的文件
*@param要替换的字符索引
*@param newChar新字符
*@如果文件不存在,则抛出FileNotFoundException
*@如果发生不好的事情,会抛出IOException
*/
私有静态void replaceChar(文件f,int索引,char newChar)
抛出FileNotFoundException,IOException{
int fileLength=(int)f.length();
如果(索引<0 | |索引>文件长度-1){
抛出新的IllegalArgumentException(“无效索引”+索引);
}
字节[]bt=新字节[(int)文件长度];
FileInputStream fis=新的FileInputStream(f);
财政司司长(bt);
StringBuffer sb=新的StringBuffer(新字符串(bt));
sb.setCharAt(索引,newChar);
FileOutputStream fos=新的FileOutputStream(f);
fos.write(sb.toString().getBytes());
fos.close();
}
但是请注意,它不适用于非常大的文件,因为f.length()被强制转换为int。对于那些文件,您应该使用通常的方法读取整个文件并将其转储到另一个文件上