How to create a folder named after the current date

Asked

Viewed 636 times

1

I am trying to create a folder with the same name as the current date but simply does not create.

import java.util.*;
import java.io.File;


public class PastaData {

Date data = new Date();
SimpleDateFormat formatar = new SimpleDateFormat("d/m/y");
String dataFormatada = new formatar.format(data);
System.out.println("dataFormatada");

File file = new File(dataFormatada);
file.mkdir();



}
  • 1

    Which path is the creation of the folder? The way it is in the code, is creating inside your project. Try this way: File file = new File("C:\" + dataFormatada); and go to this address and see if created.

  • @diegofm probably directly in C: it will not have access permission. I think it is best to create in the project folder, but not within the project.

  • 1

    @Sorack as you know he has no access?

  • Hehehehehe usually on my PC gives this, and my user is administrator

  • I tried to use the command you told me but still nothing changed :(

  • 1

    @Sorack depends on how your system is configured with security directives, or if your user is not an administrator, here it works normally without having to elevate prompt privileges, but my user is a system administrator.

  • Was any of the answer helpful? Don’t forget to choose one and mark it so it can be used if someone has a similar question!

Show 2 more comments

2 answers

4

The problem is that windows does not allow creation of files or folders with /, is an invalid character.

Change the date formatting mask to "d-m-y" and it will work normally. And don’t forget to import the class SimpleDateFormat.

the example below:

import java.util.*;
import java.io.File;
import java.text.SimpleDateFormat;


public class PastaData {

   public static void main(String[] args) {

      Date data = new Date();
      SimpleDateFormat formatar = new SimpleDateFormat("d-m-y");
      String dataFormatada = formatar.format(data);  

      try{      

         File f = new File(dataFormatada);

         System.out.println(dataFormatada);

         f.mkdir();

      }catch(Exception e){

         e.printStackTrace();
      }
   }
}

Official reference: Naming Files, Paths, and Namespaces

  • I’ll try so thank you very much!

  • @Felipemorenoborges if you serve, do not forget to click to indicate that this solution has served you. In case of any problem, just speak here :)

2

Can use LocalDate#now().toString() which returns the current date in format yyyy-mm-dd:

final String directory = LocalDate.now().toString();
Files.createDirectory(Paths.get("C:", directory)); // cria um diretório na unidade C:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.