Java - Créer un fichier

Java - Créer un fichier

Dans ce rapide didacticiel, nous allons apprendre à créer un nouveau fichier en Java - en utilisant d'abord JDK6, puis le nouveau JDK7 avec NIO et enfin la bibliothèqueApache Commons IO.

Cet article fait partie dethe “Java – Back to Basic” series ici par exemple.

1. Avec Java - JDK 6

Commençons parthe standard solution using the old JDK 6 File API:

@Test
public void givenUsingJDK6_whenCreatingFile_thenCorrect() throws IOException {
    File newFile = new File("src/test/resources/newFile_jdk6.txt");
    boolean success = newFile.createNewFile();

    assertTrue(success);
}

Notez que le fichier ne doit pas exister pour que cette opération réussisse; si le fichier existe, alors l'opérationcreateNewFile retournera false.

2. Avec Java - JDK 7

Jetons maintenant un coup d'œil à la nouvelle solution - en utilisant la prise en charge NIO2 dans JDK 7:

@Test
public void givenUsingJDK7nio2_whenCreatingFile_thenCorrect()
  throws IOException {
    Path newFilePath = Paths.get("src/test/resources/newFile_jdk7.txt");
    Files.createFile(newFilePath);
}

Comme vous pouvez le voir, le code est toujours très simple; nous utilisons maintenant la nouvelle interfacePath au lieu de l’ancienneFile.

Une chose à noter ici est que la nouvelle API fait bon usage des exceptions - si le fichier existe déjà, nous n'avons plus à vérifier un code de retour - nous obtenons unFileAlreadyExistsException à la place:

java.nio.file.FileAlreadyExistsException: srctestresourcesnewFile_jdk7.txt
    at sun.n.f.WindowsException.translateToIOException(WindowsException.java:81)

3. Avec goyave

La solution de goyave pour créer un nouveau fichier est également rapide:

@Test
public void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
    Files.touch(new File("src/test/resources/newFile_guava.txt"));
}

4. Avec Commons IO

Apache Commons fournit la méthodeFileUtils.touch() qui implémente le même comportement que l'utilitaire «touch» sous Linux - il crée un nouveau fichier vide ou même un fichier et son chemin complet dans un système de fichiers:

@Test
public void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException {
    FileUtils.touch(new File("src/test/resources/newFile_commonsio.txt"));
}

Notez que cela se comporte légèrement différemment des exemples précédents - sithe file already exists, the operation doesn’t fail - il ne fait simplement rien.

Et voilà: 4 façons rapides de créer un nouveau fichier en Java.