我正在尝试使用Java找到一种方法来删除文本文件中的第一行。 希望使用扫描仪来完成...是否有一种好的方法可以在不需要tmp文件的情况下完成?谢谢。
如果您的文件很大,您可以使用以下方法执行删除操作,它可以直接在原地进行,而无需使用临时文件或将所有内容加载到内存中。
public static void removeFirstLine(String fileName) throws IOException {
RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
//Initial write position
long writePosition = raf.getFilePointer();
raf.readLine();
// Shift the next lines upwards.
long readPosition = raf.getFilePointer();
byte[] buff = new byte[1024];
int n;
while (-1 != (n = raf.read(buff))) {
raf.seek(writePosition);
raf.write(buff, 0, n);
readPosition += n;
writePosition += n;
raf.seek(readPosition);
}
raf.setLength(writePosition);
raf.close();
}
请注意,如果在上述循环过程中终止程序,则可能会出现重复的行或损坏的文件。
Scanner fileScanner = new Scanner(myFile);
fileScanner.nextLine();
这将返回文件中的第一行文本并将其丢弃,因为您没有将其存储在任何地方。
要覆盖您现有的文件:
FileWriter fileStream = new FileWriter("my/path/for/file.txt");
BufferedWriter out = new BufferedWriter(fileStream);
while(fileScanner.hasNextLine()) {
String next = fileScanner.nextLine();
if(next.equals("\n"))
out.newLine();
else
out.write(next);
out.newLine();
}
out.close();
请注意,您需要以这种方式捕获和处理一些IOException
。此外,在while()
循环中,if()... else()...
语句对于保留文本文件中存在的任何换行符是必要的。
如果没有临时文件,您必须将所有内容保存在主内存中。其余部分很简单:循环遍历行(忽略第一行)并将它们存储在集合中。然后将这些行写回磁盘:
File path = new File("/path/to/file.txt");
Scanner scanner = new Scanner(path);
ArrayList<String> coll = new ArrayList<String>();
scanner.nextLine();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
coll.add(line);
}
scanner.close();
FileWriter writer = new FileWriter(path);
for (String line : coll) {
writer.write(line);
}
writer.close();