0

is there a way to set the maximum size of a csv file Im writing to? My program is writing every minute the current date + time into an csv file. Now I want to set the maximum size of this file to e.g. 2 MB or 1000 rows. When it reaches the limit I want the first date to be deleted and append the new date.

I could read the file into an ArrayList and check the size of it, but then I have to cache the csv file which would need a lot of memory (?). Is there another better way?

My csv file looks like this:

Date; Time
2021-10-21; 10:40:00
2021-10-21; 10:41:00
2021-10-21; 10:42:00
2021-10-21; 10:43:00 ...

And my code like this:

try {
        FileWriter writer = new FileWriter(new File("myCSV.csv"), true);
        writer.append("Date; Time\n");
        writer.close();
        while(true){
            writer = new FileWriter(new File("myCSV.csv"), true);
            writer.append(LocalDate.now() + ";" + LocalTime.now() + "\n");
            writer.close();
            Thread.sleep(60000);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

Thanks for your help!

  • Please take a look at the following https://stackoverflow.com/questions/39092861/limit-file-size-while-writing-in-java It can give you ideas on how to approach this. – JCompetence Oct 21 '21 at 09:09
  • There is no “magic” way to delete the first few lines of a file and shift the remainder forward. That means your choices are (1) have a rolling log of files (eg, start a new file every hour, Mayne deleting all but the previous as you go), or (2) use a database instead of files, or (3) when at maximum size, set the file pointer to the start of the file, so you overwrite the earlier records (you will have to keep track of the current insertion point) – racraman Oct 21 '21 at 09:52

0 Answers0