Este código comprueba primero la existencia del directorio y lo crea si no es así, y crea el archivo después. Tenga en cuenta que no pude verificar algunas de sus llamadas a métodos porque no tengo su código completo, así que supongo que las llamadas a cosas como getTimeStamp()y getClassName()funcionarán. También debe hacer algo con lo posible IOExceptionque se puede lanzar al usar cualquiera de las java.io.*clases: o su función que escribe los archivos debe lanzar esta excepción (y se maneja en otro lugar), o debe hacerlo directamente en el método. Además, asumí que ides de tipo String, no lo sé, ya que su código no lo define explícitamente. Si es algo más como an int, probablemente debería convertirlo en a Stringantes de usarlo en fileName como lo he hecho aquí.
Además, reemplacé sus appendllamadas con concato +como vi apropiado.
public void writeFile(String value){
String PATH = "/remote/dir/server/";
String directoryName = PATH.concat(this.getClassName());
String fileName = id + getTimeStamp() + ".txt";
File directory = new File(directoryName);
if (! directory.exists()){
directory.mkdir();
}
File file = new File(directoryName + "/" + fileName);
try{
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(value);
bw.close();
}
catch (IOException e){
e.printStackTrace();
System.exit(-1);
}
}
Probablemente no debería usar nombres de ruta desnudos como este si desea ejecutar el código en Microsoft Windows; no estoy seguro de qué hará con /los nombres de archivo. Para una portabilidad completa, probablemente debería usar algo como File.separator para construir sus rutas.
Editar : Según un comentario de JosefScript a continuación, no es necesario probar la existencia del directorio. La directory.mkdir() llamada regresará truesi creó un directorio, y falsesi no lo hizo, incluido el caso cuando el directorio ya existía.
mkdirs()método.versión java 8+
Files.createDirectories(Paths.get("/Your/Path/Here"));The Files.createDirectories
crea un nuevo directorio y directorios principales que no existen.
El método no genera una excepción si el directorio ya existe.
fuente
Tratando de hacer esto lo más breve y simple posible. Crea un directorio si no existe y luego devuelve el archivo deseado:
/** Creates parent directories if necessary. Then returns file */ private static File fileWithDirectoryAssurance(String directory, String filename) { File dir = new File(directory); if (!dir.exists()) dir.mkdirs(); return new File(directory + "/" + filename); }fuente
Sugeriría lo siguiente para Java8 +.
/** * Creates a File if the file does not exist, or returns a * reference to the File if it already exists. */ private File createOrRetrieve(final String target) throws IOException{ final Path path = Paths.get(target); if(Files.notExists(path)){ LOG.info("Target file \"" + target + "\" will be created."); return Files.createFile(Files.createDirectories(path)).toFile(); } LOG.info("Target file \"" + target + "\" will be retrieved."); return path.toFile(); } /** * Deletes the target if it exists then creates a new empty file. */ private File createOrReplaceFileAndDirectories(final String target) throws IOException{ final Path path = Paths.get(target); // Create only if it does not exist already Files.walk(path) .filter(p -> Files.exists(p)) .sorted(Comparator.reverseOrder()) .peek(p -> LOG.info("Deleted existing file or directory \"" + p + "\".")) .forEach(p -> { try{ Files.createFile(Files.createDirectories(p)); } catch(IOException e){ throw new IllegalStateException(e); } }); LOG.info("Target file \"" + target + "\" will be created."); return Files.createFile( Files.createDirectories(path) ).toFile(); }fuente
Files.createFile(Files.createDirectories(path)).toFile()debería serFiles.createDirectories(path).toFile()por laAccess Deniedrazón.Files.createFile(Files.createDirectories(path))no funciona como se describe en el comentario anterior.createDirectoriesya crea un directorio con el nombre del archivo, por ejemplo, "test.txt", porcreateFilelo que fallará.código:
// Create Directory if not exist then Copy a file. public static void copyFile_Directory(String origin, String destDir, String destination) throws IOException { Path FROM = Paths.get(origin); Path TO = Paths.get(destination); File directory = new File(String.valueOf(destDir)); if (!directory.exists()) { directory.mkdir(); } //overwrite the destination file if it exists, and copy // the file attributes, including the rwx permissions CopyOption[] options = new CopyOption[]{ StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES }; Files.copy(FROM, TO, options); }fuente
Usarlo
java.nio.Pathsería bastante simple:public static Path createFileWithDir(String directory, String filename) { File dir = new File(directory); if (!dir.exists()) dir.mkdirs(); return Paths.get(directory + File.separatorChar + filename); }fuente
Si crea una aplicación basada en web, la mejor solución es verificar que el directorio exista o no y luego crear el archivo si no existe. Si existe, vuelva a crear.
private File createFile(String path, String fileName) throws IOException { ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource(".").getFile() + path + fileName); // Lets create the directory try { file.getParentFile().mkdir(); } catch (Exception err){ System.out.println("ERROR (Directory Create)" + err.getMessage()); } // Lets create the file if we have credential try { file.createNewFile(); } catch (Exception err){ System.out.println("ERROR (File Create)" + err.getMessage()); } return file; }fuente