如何删除java中的文本文件的第一行

可能重复:
用Java替换文本文件的第一行
Java – 在文件中查找一行并删除

我试图找到一种方法来使用java删除文本文件中的第一行文本。 想用扫描仪做它…有没有一个很好的方法来做它而不需要tmp文件?

谢谢。

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()...语句在while()循环中是必需的,以保持文本文件中存在任何换行符。

如果您的文件很大,您可以使用以下方法在不使用临时文件或将所有内容加载到内存中的情况下执行删除。

 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(); } 

请注意,如果您的程序在上述循环中间终止,则最终可能会出现重复的行或损坏的文件。

如果文件不是太大,你可以读入一个字节数组,找到第一个新的行符号,并将其余的数组写入从零位开始的文件。 或者您可以使用内存映射文件来执行此操作。

没有临时文件,您必须将所有内容保存在主内存中 其余的是直截了当的:循环(忽略第一个)并将它们存储在一个集合中。 然后将行写回磁盘:

 File path = new File("/path/to/file.txt"); Scanner scanner = new Scanner(path); ArrayList coll = new ArrayList(); 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();