Java FileWriter

Java FileWriter

1. Visão geral

Neste tutorial, vamos aprender e entender a classeFileWriter presente no pacotejava.io.

2. FileWriter

FileWriter is aspecializedOutputStreamWriterfor writing character files. Ele não expõe nenhuma operação nova, mas funciona com as operações herdadas das classesOutputStreamWritereWriter.

Até o Java 11, oFileWriter funcionava com a codificação de caracteres padrão e o tamanho do buffer de bytes padrão. No entanto,Java 11 introduced four new constructors that accept a Charset, thereby allowing user-specified Charset. Infelizmente, ainda não podemos modificar o tamanho do buffer de bytes e ele está definido como 8192.

2.1. Instanciando oFileWriter

Existem cinco construtores na classeFileWriter se estivermos usando uma versão Java anterior ao Java 11.

Vamos dar uma olhada em vários construtores:

public FileWriter(String fileName) throws IOException {
    super(new FileOutputStream(fileName));
}

public FileWriter(String fileName, boolean append) throws IOException {
    super(new FileOutputStream(fileName, append));
}

public FileWriter(File file) throws IOException {
    super(new FileOutputStream(file));
}

public FileWriter(File file, boolean append) throws IOException {
    super(new FileOutputStream(file, append));
}

public FileWriter(FileDescriptor fd) {
    super(new FileOutputStream(fd));
}

O Java 11 apresentou quatro construtores adicionais:

public FileWriter(String fileName, Charset charset) throws IOException {
    super(new FileOutputStream(fileName), charset);
}

public FileWriter(String fileName, Charset charset, boolean append) throws IOException {
    super(new FileOutputStream(fileName, append), charset);
}

public FileWriter(File file, Charset charset) throws IOException {
    super(new FileOutputStream(file), charset);
}

public FileWriter(File file, Charset charset, boolean append) throws IOException {
    super(new FileOutputStream(file, append), charset);
}

2.2. Escrevendo umString para um arquivo

Vamos agora usar um dos construtoresFileWriter para criar uma instância deFileWritere gravar em um arquivo:

try (FileWriter fileWriter = new FileWriter("src/test/resources/FileWriterTest.txt")) {
    fileWriter.write("Hello Folks!");
}

Usamos o construtor de argumento único deFileWriter que aceita um nome de arquivo. Em seguida, usamos a operaçãowrite(String str) herdada do sclassWriter . Since the FileWriter is AutoCloseable, we’ve used try-with-resources so that we don’t have to close the FileWriter explicitly.

Ao executar o código acima, oString será gravado no arquivo especificado:

Hello Folks!

The FileWriter does not guarantee whether the FileWriterTest.txt file will be available or be created. Depende da plataforma subjacente.

Também devemos observar que certas plataformas podem permitir apenas uma única instânciaFileWriter para abrir o arquivo. Nesse caso, os outros construtores da classeFileWriter falharão se o arquivo envolvido já estiver aberto.

2.3. Anexando umString a um arquivo

Geralmente, precisamos anexar dados ao conteúdo existente de um arquivo. Vejamos agora um exemplo deFileWriter que suporta anexação:

try (FileWriter fileWriter = new FileWriter("src/test/resources/FileWriterTest.txt", true)) {
    fileWriter.write("Hello Folks Again!");
}

Como podemos ver, usamos o construtor de dois argumentos que aceita um nome de arquivo e um sinalizadorbooleanappend. Passing the flag append as true creates a FileWriter that allows us to append text to existing contents of a file.

Ao executar o código, teremosString anexado ao conteúdo existente do arquivo especificado:

Hello Folks!Hello Folks Again!

3. Conclusão

Neste artigo, aprendemos sobre a classe de conveniênciaFileWriter e algumas maneiras de criarFileWriter. Nós então o usamos para gravar dados em um arquivo.

Como sempre, o código-fonte completo do tutorial está disponívelover on GitHub.