java 从最后一行检查内容,将符合要求的那一行删除
时间: 2023-09-08 21:11:13 浏览: 44
要在Java中从文件的最后一行开始检查内容,并删除符合要求的行,你可以使用类似于以下的代码:
```
import java.io.*;
public class RemoveLastLineFromFile {
public static void main(String[] args) {
removeLastLine("file.txt", "delete this line");
}
public static void removeLastLine(String fileName, String lineToRemove) {
try {
File inFile = new File(fileName);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//读取文件
RandomAccessFile file = new RandomAccessFile(inFile, "rw");
long fileLength = inFile.length();
long filePointer = fileLength - 1;
//从文件的末尾开始逐个字符地读取内容
while (filePointer > 0) {
file.seek(filePointer);
if (file.readByte() == '\n') {
break;
}
filePointer--;
}
//删除符合要求的行
String currentLine;
while ((currentLine = file.readLine()) != null) {
if (currentLine.equals(lineToRemove)) {
long writePointer = file.getFilePointer();
file.seek(filePointer);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = file.read(buffer)) != -1) {
file.write(buffer, 0, bytesRead);
}
file.setLength(writePointer);
file.close();
return;
}
filePointer = file.getFilePointer();
}
file.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
```
在这个例子中,我们将文件名和要删除的行内容作为参数传递给`removeLastLine()`方法。该方法打开文件并从文件的末尾开始逐个字符地读取内容。当找到换行符时,我们就知道我们已经到达了最后一行。然后,我们从文件的末尾向前读取每一行,并删除符合要求的那一行。最后,我们将文件截断为正确的长度并关闭文件。
请注意,这种方法不适用于二进制文件,因为它假定每一行都以换行符结尾。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
Cause: java.sql.SQLException: ORA-06550: 第 26 行, 第 10 列: \nPLS-00103: Encountered the symbol \",\" when expecting one of the following:\n\n ( begin case declare end exception exit for goto if loop mod\n null pragma raise return select update while with\n <an identifier> \n << continue close current delete fetch lock\n insert open rollback savepoint set sql execute commit forall\n merge pipe purge\nThe symbol \",\" was ignored.\nORA-0655
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)