1

i'm new here and i learn Java. My english is not the best.

I need some help and would be grateful if you could help me.

I want to code a program in Java which store log data in a CSV-file. The application starts if i turn the computer on.

The program creates a CSV-file for the current month and before this happen must check if did exist for the current month.

The date and the time must be saved.this must be also checked if this current date exist. i want to store the date and time of Power On and OFF. Attention: i can shutdown many times , but they store update date.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.io.BufferedReader;

public class LoggerApp {

    public static void main(String[] args) {

        // Creates a CSV File with current Year and Month
        String fileName = new SimpleDateFormat("MM-yyyy'.csv'").format(new Date());

        // Proof of File exist and read the file
        File f = new File(fileName);
        if (f.exists() && !f.isDirectory()) {
            FileReader fr = null;
            try {
                fr = new FileReader(f);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            BufferedReader br = new BufferedReader(fr);

        } else {
            String fileName1 = new SimpleDateFormat("MM-yyyy'.csv'").format(new Date());
        }

        FileWriter writer;
        File datei = new File(fileName);
        // LocalDateTime currentDateTime = LocalDateTime.now();

        try {
            LocalDateTime currentDateTime = LocalDateTime.now();
            // System.out.println("Before formatting: " + currentDateTime);

            writer = new FileWriter(datei);
            // writer.write(currentDateTime.toString());
            DateTimeFormatter changeDateTimeFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
            writer.write(System.getProperty("line.separator"));

            String formattedDate = changeDateTimeFormat.format(currentDateTime);
            writer.write(formattedDate);
            writer.flush();
            writer.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

}
iLearnJava
  • 13
  • 4

2 Answers2

2

Avoid legacy date-time classes

You are mixing the troublesome legacy date-time classes such as SimpleDateFormat and Date with their modern replacements in the java.time packages. Don’t do this. Use only the java.time classes.

File name

I suggest using ISO 8601 style naming for your files. Text in these formats when sorted alphabetically will be in chronological order.

Apparently you want only year and month for the file name. The ISO 8601 standard for that is YYYY-MM.

Getting the current year-month requires a time zone. For any given moment the date varies around the globe by zone. If the current moment is near the end/beginning of a month, the year-month could by next month in one place while simultaneously last month in another.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
YearMonth yearMonth = YearMonth.now( z ) ;       // Get current year-month as seen in a particular time zone.

Make the file name text.

String fileName = yearMonth.toString() + ".csv" ;

To generate text representing the date and time-of-day, use ZonedDateTime.

ZonedDateTime zdt = ZonedDateTime.now( z ) ;
String output = zdt.toString() ;

You can obtain an YearMonth from that moment.

YearMonth yearMonth = YearMonth.from( zdt ) ;

File existence

Apparently you want to create a file only if it does not yet exist.

Java has some legacy classes for dealing with files, such as java.io.File. And Java has a newer, more modern set of classes for files and input/output called “NIO” (non-blocking I/O). See Oracle Tutorial.

String filePathString = "/Users/basilbourque/" + fileName ;
Path path = Paths.get( filePathString );

if ( Files.exists(path) ) {
     … do nothing
}

if ( Files.notExists(path) ) {
     … proceed with creating new file
}

CSV

Creating CSV files has been covered many times on Stack Overflow. Search to learn more.

I suggest using a library to help with the chore of generating or parsing CSV or tab-delimited files. I have made good use of Apache Commons CSV. And there are others as well.

I myself have shared example demoing writing of CSV files here, here, here, and likely others.

Machine bootup/shutdown

The application starts if i turn the computer on.

The date and the time must be saved.this must be also checked if this current date exist. i want to store the date and time of Power On and OFF.

I cannot help you there. I do not know about hooking into bootup/shutdown via Java. I imagine you could write a shell script to invoke your Java app. Then configure some OS-specific mechanism to execute the shell script at the appropriate time.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

I suggest exploring existing logging tools, Log4J is one of the mostly used, depending upon what and how you want to put in this log, you can get this log contents as CSV if that is your requirement, or these logs can alter be converted to CSV through program if you are further processing them.

Mayank J
  • 71
  • 3