1

I have a file have lot of records in millions. here I want to read first 2000 records and delete them after read. i am able to read record but please let me know how to delete.

public class Files {


    public static void files(int index) throws IOException {
        try {

            //numbers num = new numbers();
            BufferedReader br = null;
            BufferedWriter bw = null;
            try {

                String sCurrentLine = "";
                br = new BufferedReader(new FileReader("data.txt"));
                bw = new BufferedWriter(new FileWriter("File_2.txt"));

                int i = 0;
                while ((sCurrentLine = br.readLine()) != null && i < index) {
                    System.out.println(++i + " " + sCurrentLine);
                    bw.write(sCurrentLine);
                    bw.write(System.getProperty("line.separator"));
                    //sCurrentLine = br.readLine();
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    br.close();
                    bw.close();
                    if (br != null) {
                        br.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

        } catch (Exception e) {

        }
    }

}
Filburt
  • 17,626
  • 12
  • 64
  • 115
GulZaib Amjed
  • 81
  • 1
  • 6

1 Answers1

0

You have several options: If you want to update the existing file - read and write at the same time, you will need a RandomAccessFile stream. With that you can open file for both - reading and writing. On the other hand, it might be risky to update the same file without keeping original, as your application might crash at some point and you will be left with a damaged file.

Another way would be take a new temporary file and write the part you'd like to keep in that file, but if you have millions of records, this might not be efficient.

Samurai Girl
  • 978
  • 2
  • 8
  • 13