Click here to Skip to main content
15,896,487 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i am creating a program that will create a text file and write hello world
if the program is run twice on the same day the textfile should contain 2 hello world and if it is run on the same day but different month it should erase the existing written text and write another hello world;

What I have tried:

Java
Calendar calendar = Calendar.getInstance();
    Date date = new Date();
    calendar.setTime(date);
    int month = calendar.get(Calendar.DAY_OF_MONTH);
   
   File myFile = new File("log_"+month+".txt");
    if(!myFile.exists())
    {
        myFile.createNewFile();
        PrintWriter out = new PrintWriter(myFile);
        out.write("Hello World"+System.lineSeparator());
        out.close();
        System.out.print("First Creation");
        return;
    }

     if(myFile.exists())
   {
      
        Path p = Paths.get(myFile.toString());
     BasicFileAttributes attr = Files.readAttributes(p, BasicFileAttributes.class);
  
     FileTime creation = attr.creationTime();
     DateFormat df = new SimpleDateFormat("MM:dd");
     String x = df.format(creation.toMillis());
     String y = new SimpleDateFormat("MM:dd").format(calendar.getTime());
     attr = null;
     if((x).equals(y))
       {
         FileWriter fw = new FileWriter(myFile.getAbsoluteFile(),true);
   BufferedWriter output = new BufferedWriter(fw);
         output.write("Hello World" +System.lineSeparator());
         output.close();
         System.out.print("Existing");
         df = null;
       }
      else {
      
           myFile.delete();
            myFile.createNewFile();
    PrintWriter out = new PrintWriter(myFile);
    out.write("Hello World"+System.lineSeparator());
    out.close();
           System.out.print(x+y);
          
      }
   }
Posted
Updated 29-May-17 23:07pm
v2
Comments
OriginalGriff 30-May-17 4:31am    
And?
What does it do that you didn't expect, or not do that you did?
What have you tried to find out why?
Where are you stuck?
What help do you need?
Use the "Improve question" widget to edit your question and provide better information.

1 solution

You seem to be mixing your types and the actual logic you need. The steps should be:

  1. If the file does not exist, then create it.
  2. If the create month of the file is not this month then delete it, and create a new file.
  3. Open the file for output with append.
  4. Seek to the end of the file.
  5. Write your text to the file.
  6. Close the file.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900