How to create a folder with the current date name

1

I'm trying to create a folder with the name equal to the current date but it just 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();



}
    
asked by anonymous 03.11.2016 / 22:56

2 answers

4

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

Change the date formatting mask to% cos_de% and it will work normally. And do not forget to import the "d-m-y" class.

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

    
03.11.2016 / 23:13
2

You can use LocalDate#now().toString() to return the current date in yyyy-mm-dd format:

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