Java - Criar um arquivo
Neste tutorial rápido, vamos aprender como criar um novo arquivo em Java - primeiro usando JDK6, depois o JDK7 mais recente com NIO e, finalmente, a bibliotecaApache Commons IO.
Este artigo faz parte dethe “Java – Back to Basic” series aqui no exemplo.
1. Com Java - JDK 6
Vamos começar comthe 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);
}
Observe que o arquivo não deve existir para que esta operação seja bem-sucedida; se o arquivo existir, a operaçãocreateNewFile retornará falso.
2. Com Java - JDK 7
Vamos agora dar uma olhada na solução mais recente - usando o suporte NIO2 no JDK 7:
@Test
public void givenUsingJDK7nio2_whenCreatingFile_thenCorrect()
throws IOException {
Path newFilePath = Paths.get("src/test/resources/newFile_jdk7.txt");
Files.createFile(newFilePath);
}
Como você pode ver, o código ainda é muito simples; agora estamos usando a nova interfacePath em vez da antigaFile.
Uma coisa a observar aqui é que a nova API faz bom uso de exceções - se o arquivo já existir, não precisamos mais verificar um código de retorno - obtemos umFileAlreadyExistsException em vez disso:
java.nio.file.FileAlreadyExistsException: srctestresourcesnewFile_jdk7.txt
at sun.n.f.WindowsException.translateToIOException(WindowsException.java:81)
3. Com goiaba
A solução Guava para criar um novo arquivo também é rápida:
@Test
public void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
Files.touch(new File("src/test/resources/newFile_guava.txt"));
}
4. Com Commons IO
O Apache Commons fornece o métodoFileUtils.touch() que implementa o mesmo comportamento do utilitário “touch” no Linux - ele cria um novo arquivo vazio ou até mesmo um arquivo e o caminho completo para ele em um sistema de arquivos:
@Test
public void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException {
FileUtils.touch(new File("src/test/resources/newFile_commonsio.txt"));
}
Observe que isso se comporta de maneira ligeiramente diferente dos exemplos anteriores - sethe file already exists, the operation doesn’t fail - simplesmente não faz nada.
E aqui temos - 4 maneiras rápidas de criar um novo arquivo em Java.