Crear una ruta completa automáticamente al escribir en un archivo nuevo


Quiero escribir un nuevo archivo con el FileWriter. Lo uso así:

FileWriter newJsp = new FileWriter("C:\\user\Desktop\dir1\dir2\filename.txt");

Ahora dir1 y dir2 actualmente no existen. Quiero que Java los cree automáticamente si aún no están allí. En realidad, Java debería configurar toda la ruta del archivo si no existe ya.

¿Cómo puedo lograr esto?

Author: Jon Skeet, 2010-05-14

5 answers

Algo como:

File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
 338
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-14 11:53:41

Desde Java 1.7 se pueden usar archivos.CreateFile:

Path pathToFile = Paths.get("/home/joe/foo/bar/myFile.txt");
Files.createDirectories(pathToFile.getParent());
Files.createFile(pathToFile);
 106
Author: cdmihai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-25 17:36:07

Use File.mkdirs():

File dir = new File("C:\\user\\Desktop\\dir1\\dir2");
dir.mkdirs();
File file = new File(dir, "filename.txt");
FileWriter newJsp = new FileWriter(file);
 22
Author: Armand,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-14 11:53:30
 14
Author: Marcelo Cantos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-14 11:53:13

Use FileUtils para manejar todos estos dolores de cabeza.

Editar: Por ejemplo, use el código de abajo para escribir en un archivo, este método 'comprobará y creará el directorio padre si no existe'.

openOutputStream(File file [, boolean append]) 
 4
Author: kakacii,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-08 03:52:37