import java.io.RandomAccessFile;
import java.util.ArrayList;
public class DeleteFirstLineForTxt {
public static void main(String[] args) throws Exception{
String path ="D://1//data.txt";
deleteFirstLineForTxt(path);
System.out.println("OK");
}
public static String deleteFirstLineForTxt(String path) throws Exception {
long start = System.currentTimeMillis();
RandomAccessFile raf = new RandomAccessFile(path, "rw");
//Initial write position
long writePosition = raf.getFilePointer();
String username = raf.readLine().replace("\n", "").replace("\r", "").trim();
// 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();
System.out.println("username: " + username);
long end = System.currentTimeMillis();
long cost = end - start;
System.out.println("cost: " + cost);
return username;
}
}
如果您的文件很大,则可以使用以下方法在不使用临时文件或将所有内容加载到内存中的情况下执行删除.
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();
}
请注意,如果您的程序在上述循环中间终止,则最终可能会出现重复的行或损坏的文件.
ast*_*eri 9
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这种方式捕捉和处理某些内容.此外,if()... else()...语句在while()循环中是必要的,以保持文本文件中存在任何换行符.