How to delete the first line of a text file in java

Possible duplicate:
Replace the first line of a text file in Java
Java - find line in file and delete

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

Thanks.

+4
source share
4 answers
Scanner fileScanner = new Scanner(myFile); fileScanner.nextLine(); 

This will return the first line of text from the file and discard it, because you do not store anything in it.

To overwrite an 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 catch and handle some IOException this way. In addition, the if()... else()... needed in the while() to save any line breaks in a text file.

+8
source

If your file is huge, you can use the following method, which does the deletion in place, without using a temporary file or loading all the contents 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(); } 

Please note that if your program terminates in the middle of the above loop, you may get duplicate lines or a damaged file.

+14
source

If the file is not too large, you can read it into an array of bytes, find the first new character of the string and write the rest of the array to the file, starting at position zero. Or you can use a memory mapped file for this.

0
source

Without a temporary file, you must store everything in main memory. The rest is straightforward: loop over the lines (ignoring the first) and save 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(); 
0
source

Source: https://habr.com/ru/post/1443445/


All Articles