6

Possible Duplicate:
Replace first line of a text file in Java
Java - Find a line in a file and remove

I am trying to find a way to remove the first line of text in a text file using java. Would like to use a scanner to do it...is there a good way to do it without the need of a tmp file?

Thanks.

Community
  • 1
  • 1
Butterflycode
  • 759
  • 2
  • 10
  • 23
  • For many uses, you should always use a temp file on the same partition, then use rename/move operation of the OS to atomically replace old file with the new, so the file is never only partially written. – hyde Nov 01 '12 at 13:53

4 Answers4

18

If your file is huge, you can use the following method that is performing the remove, in place, without using a temp file or loading all the content into memory.

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

Note that if your program is terminated while in the middle of the above loop you can end up with duplicated lines or corrupted file.

dan
  • 13,132
  • 3
  • 38
  • 49
14
Scanner fileScanner = new Scanner(myFile);
fileScanner.nextLine();

This will return the first line of text from the file and discard it because you don't store it anywhere.

To overwrite your existing file:

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

Note that you will have to be catching and handling some IOExceptions this way. Also, the if()... else()... statement is necessary in the while() loop to keep any line breaks present in your text file.

PenguinEngineer
  • 295
  • 1
  • 8
  • 30
asteri
  • 11,402
  • 13
  • 60
  • 84
1

Without temp file you must keep everything in main memory. The rest is straight forward: loop over the lines (ignoring the first) and store them in a collection. Then write the lines back to disk:

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();
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
0

If file is not too big, you can read is into a byte array, find first new line symbol and write the rest of array into the file starting from position zero. Or you may use memory mapped file to do so.

kofemann
  • 4,217
  • 1
  • 34
  • 39