Nick
Nick

Reputation: 150

Can't create folder using DateTime as name

I am trying to create a folder using a TimeStamp as the folder name. The code I am using will not create the folder when I use the timeStamp variable in the code below. However if I set the folder name directly like this ...

File dir = new File("Hello") 

The folder is created. Is this the right way to set a folder name using Date and time?

public void logEmData(String reason,Campus c ) throws IOException 
{

    LocalDateTime time = LocalDateTime.now();

    try(FileWriter writer = new FileWriter(file, true))
    {
        writer.write("Building " + c.getName() + " Entered Emergency Mode" + System.lineSeparator());

        writer.write(" Reason: " + reason + System.lineSeparator());

        writer.write(time.toString() + System.lineSeparator());

       //Create folder 
        String timeStamp = "EM_" + time;
        File dir = new File(timeStamp);
        dir.mkdir();

    }

Upvotes: 5

Views: 2157

Answers (4)

Dherik
Dherik

Reputation: 19060

The LocalDateTime.now.toString() produces a String like:

2018-01-01T00:00:00.000

On Windows this is not a valid directory name, because the : char is not permitted on directory names.

So, you can remove the : or replace with something else:

 String directoryName = LocalDateTime.now.toString().replaceAll(":", "");

Upvotes: 0

mech
mech

Reputation: 2913

LocalDateTime.now() gets you a date with a format roughly like so: 2015-01-14T16:00:49.455.

: is a problematic character for folder creation under Windows due to it being a reserved character. You may want to consider formatting the string to change it to -.

Upvotes: 4

Most date formats contain characters that Windows will choke on, particularly MM/dd/yyyy (\) or anything that includes the time (:).

The best approach, which also has the advantage of sorting lexically, is to use the ISO-8601 format of YYYY-MM-dd, or if you absolutely need time information, using underscores as separators instead of colons.

Upvotes: 1

eg04lt3r
eg04lt3r

Reputation: 2610

Use Java NIO2 for this purposes.

Files.createDirectory(Paths.get("path-to-dir"));

I think it will help. And use custom formatting for date such as MM-dd-yyyy.

Upvotes: 0

Related Questions