Como faço para criar um arquivo e escrever em Java?

Qual é a maneira mais simples de criar e escrever para um arquivo (texto) em Java?

 1172
Author: Wolf, 2010-05-21

30 answers

Note que cada uma das amostras de código abaixo pode lançar IOException. Os blocos de tentativa/captura / finalmente foram omitidos por brevidade. Veja este tutorial para obter informações sobre o tratamento de excepções.

Criar um ficheiro de texto (lembre-se que isto irá sobrepor o ficheiro se já existir):

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();

Criar um ficheiro binário (isto também irá sobrepor o ficheiro):

byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();

Java 7+ os utilizadores podem utilizar o Files classe para onde escrever ficheiros:

Criar um ficheiro de texto:

List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, Charset.forName("UTF-8"));
//Files.write(file, lines, Charset.forName("UTF-8"), StandardOpenOption.APPEND);

Criar um ficheiro binário:

byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);
 1499
Author: Michael, 2018-04-16 00:04:58

Em Java 7 e acima:

try (Writer writer = new BufferedWriter(new OutputStreamWriter(
              new FileOutputStream("filename.txt"), "utf-8"))) {
   writer.write("something");
}

Existem utilitários úteis para isso embora:

Note também que você Pode usar um FileWriter, mas ele usa a codificação predefinida, que é muitas vezes uma má ideia - é melhor especificar a codificação explicitamente.

Abaixo está a resposta original, anterior a Java 7


Writer writer = null;

try {
    writer = new BufferedWriter(new OutputStreamWriter(
          new FileOutputStream("filename.txt"), "utf-8"));
    writer.write("Something");
} catch (IOException ex) {
    // Report
} finally {
   try {writer.close();} catch (Exception ex) {/*ignore*/}
}

Ver também: Ler, Escrever e criar ficheiros (inclui o NIO2).

 364
Author: Bozho, 2018-02-27 17:55:37

Se já tiver o conteúdo que deseja escrever no ficheiro( e não for gerado na altura), o java.nio.file.Files a adição em Java 7 como parte do I/O nativo fornece a maneira mais simples e eficiente de alcançar seus objetivos.

Basicamente criar e escrever num ficheiro é apenas uma linha, além disso uma simples chamada de método !

O seguinte exemplo cria e escreve para 6 ficheiros diferentes para mostrar como pode ser usado:

Charset utf8 = StandardCharsets.UTF_8;
List<String> lines = Arrays.asList("1st line", "2nd line");
byte[] data = {1, 2, 3, 4, 5};

try {
    Files.write(Paths.get("file1.bin"), data);
    Files.write(Paths.get("file2.bin"), data,
            StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    Files.write(Paths.get("file3.txt"), "content".getBytes());
    Files.write(Paths.get("file4.txt"), "content".getBytes(utf8));
    Files.write(Paths.get("file5.txt"), lines, utf8);
    Files.write(Paths.get("file6.txt"), lines, utf8,
            StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch (IOException e) {
    e.printStackTrace();
}
 118
Author: icza, 2015-02-11 07:55:13
public class Program {
    public static void main(String[] args) {
        String text = "Hello world";
        BufferedWriter output = null;
        try {
            File file = new File("example.txt");
            output = new BufferedWriter(new FileWriter(file));
            output.write(text);
        } catch ( IOException e ) {
            e.printStackTrace();
        } finally {
          if ( output != null ) {
            output.close();
          }
        }
    }
}
 70
Author: Eric Petroelje, 2016-04-13 23:04:45

Aqui está um pequeno programa de exemplo para criar ou sobrepor um arquivo. É a versão longa para que possa ser compreendida mais facilmente.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class writer {
    public void writing() {
        try {
            //Whatever the file path is.
            File statText = new File("E:/Java/Reference/bin/images/statsTest.txt");
            FileOutputStream is = new FileOutputStream(statText);
            OutputStreamWriter osw = new OutputStreamWriter(is);    
            Writer w = new BufferedWriter(osw);
            w.write("POTATO!!!");
            w.close();
        } catch (IOException e) {
            System.err.println("Problem writing to the file statsTest.txt");
        }
    }

    public static void main(String[]args) {
        writer write = new writer();
        write.writing();
    }
}
 39
Author: Draeven, 2014-11-17 20:22:44

Utilizar:

try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myFile.txt"), StandardCharsets.UTF_8))) {
    writer.write("text to write");
} 
catch (IOException ex) {
    // Handle me
}  

Se usar try() irá fechar o fluxo automaticamente. Esta versão é curta, rápida (buffer) e permite escolher a codificação.

Este recurso foi introduzido no Java 7.

 31
Author: icl7126, 2017-01-14 15:54:24

Uma forma muito simples de criar e escrever num ficheiro em Java:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class CreateFiles {

    public static void main(String[] args) {
        try{
            // Create new file
            String content = "This is the content to write into create file";
            String path="D:\\a\\hi.txt";
            File file = new File(path);

            // If file doesn't exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);

            // Write in file
            bw.write(content);

            // Close connection
            bw.close();
        }
        catch(Exception e){
            System.out.println(e);
        }
    }
}

Referência: ficheiro criar exemplo em java

 30
Author: Java Rocks, 2017-01-14 16:04:39

Aqui estamos a introduzir um texto num ficheiro de texto:

String content = "This is the content to write into a file";
File file = new File("filename.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close(); // Be sure to close BufferedWriter

Nós podemos facilmente criar um novo arquivo e adicionar conteúdo nele.

 17
Author: iKing, 2017-01-14 15:56:22

Se você deseja ter uma experiência relativamente livre de dor, Você também pode dar uma olhada no Apache Commons IO pacote , mais especificamente o FileUtils classe

Nunca se esqueça de verificar as bibliotecas de terceiros. Tempo de Joda {[5] } para manipulação de data, Apache Commons Lang StringUtils para operações de cadeia de caracteres comuns e tal pode tornar o seu código mais legível.

Java é uma grande linguagem, mas a biblioteca padrão às vezes é um pouco de baixo nível. Poderoso, mas mesmo assim, de baixo nível.

 15
Author: extraneon, 2014-01-30 23:41:00

, uma vez que o autor não especificou se precisam de uma solução para Java versões que foram EoL tinha (pelo Sun e IBM, e estes são, tecnicamente, o mais difundido JVMs), e devido ao fato de que a maioria das pessoas parecem ter respondido o autor da pergunta anterior, foi especificado que é um texto (não binário) arquivo, eu decidi para fornecer minha resposta.


Em Primeiro Lugar, Java 6 geralmente chegou ao fim da vida, e como o autor não especificou as suas necessidades compatibilidade legada, eu acho que significa automaticamente Java 7 ou acima (Java 7 ainda não é Eol'D por IBM). Então, podemos olhar para o tutorial file I/O: https://docs.oracle.com/javase/tutorial/essential/io/legacy.html

Antes do lançamento Java SE 7, a classe de Ficheiros java.io. era a mecanismo usado para Arquivo I / O, mas teve vários inconvenientes.

    Muitos métodos não abriram excepções quando falharam. impossível obter um erro útil mensagem. Por exemplo, se um ficheiro a exclusão falhou, o programa receberia uma "exclusão falha", mas não saberia se fosse porque o ficheiro não existia, o utilizador não ter permissões, ou havia outro problema.
  • o método de mudança de nome não funcionava consistentemente nas plataformas.
  • Não havia apoio real. para ligações simbólicas.
  • era desejado mais suporte para metadados, tais como: permissões de arquivos, dono de arquivo e outros atributos de segurança. Acesso os metadados dos ficheiros eram ineficientes.
  • Muitos dos métodos de Arquivo não escalaram. Pedir uma grande lista de directórios sobre um servidor pode resultar num pendurar. Pastas grandes também podem causar problemas de recursos de memória, resultando em uma negação de serviço. Não era possível escrever código confiável que poderia percorrer recursivamente uma árvore de arquivos e responder apropriadamente se houvesse ligações simbólicas circulares.
Bem, isso exclui java. io. File. o arquivo não pode ser escrito/adicionado, você pode nem mesmo ser capaz de saber por que.

Podemos continuar a olhar para o tutorial: https://docs.oracle.com/javase/tutorial/essential/io/file.html#common

Se tiver todas as linhas que irá escrever (anexar) ao ficheiro de texto com antecedência, a abordagem recomendada e https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-java.lang.Iterable-java.nio.charset.Charset-java.nio.file.OpenOption...-

Aqui está um exemplo (simplificado):

Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, StandardCharsets.UTF_8);

Outro exemplo (append):

Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE);

Se você quiser escrever o conteúdo do arquivo como você vai.: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#newBufferedWriter-java.nio.file.Path-java.nio.charset.Charset-java.nio.file.OpenOption...-

Exemplo simplificado (Java 8 ou up):

Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file)) {
    writer.append("Zero header: ").append('0').write("\r\n");
    [...]
}

Outro exemplo (append):

Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE)) {
    writer.write("----------");
    [...]
}

Estes métodos requerem um esforço mínimo por parte do autor e devem ser preferidos a todos os outros quando escrevem para [texto] ficheiros.

 11
Author: afk5min, 2018-02-27 18:38:29

Se por alguma razão quiser separar o acto de criação e escrita, o equivalente Java de touch é

try {
   //create a file named "testfile.txt" in the current working directory
   File myFile = new File("testfile.txt");
   if ( myFile.createNewFile() ) {
      System.out.println("Success!");
   } else {
      System.out.println("Failure!");
   }
} catch ( IOException ioe ) { ioe.printStackTrace(); }

createNewFile() faz uma verificação de existência e Arquivo Criar atomicamente. Isso pode ser útil se você quiser garantir que você foi o criador do arquivo antes de escrever para ele, por exemplo.

 9
Author: Mark Peters, 2010-05-21 20:12:21

Utilizar:

JFileChooser c = new JFileChooser();
c.showOpenDialog(c);
File writeFile = c.getSelectedFile();
String content = "Input the data here to be written to your file";

try {
    FileWriter fw = new FileWriter(writeFile);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.append(content);
    bw.append("hiiiii");
    bw.close();
    fw.close();
}
catch (Exception exc) {
   System.out.println(exc);
}
 9
Author: Rohit ZP, 2017-01-14 15:58:30
Acho que este é o caminho mais curto.
FileWriter fr = new FileWriter("your_file_name.txt"); // After '.' write
// your file extention (".txt" in this case)
fr.write("Things you want to write into the file"); // Warning: this will REPLACE your old file content!
fr.close();
 8
Author: ben, 2017-01-14 16:00:34

Para criar um ficheiro sem substituir o ficheiro existente:

System.out.println("Choose folder to create file");
JFileChooser c = new JFileChooser();
c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
c.showOpenDialog(c);
c.getSelectedFile();
f = c.getSelectedFile(); // File f - global variable
String newfile = f + "\\hi.doc";//.txt or .doc or .html
File file = new File(newfile);

try {
    //System.out.println(f);
    boolean flag = file.createNewFile();

    if(flag == true) {
        JOptionPane.showMessageDialog(rootPane, "File created successfully");
    }
    else {
        JOptionPane.showMessageDialog(rootPane, "File already exists");
    }
    /* Or use exists() function as follows:
        if(file.exists() == true) {
            JOptionPane.showMessageDialog(rootPane, "File already exists");
        }
        else {
            JOptionPane.showMessageDialog(rootPane, "File created successfully");
        }
    */
}
catch(Exception e) {
    // Any exception handling method of your choice
}
 7
Author: aashima, 2017-01-14 15:57:17
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExample {
    public static void main(String [] args) {
        FileWriter fw= null;
        File file =null;
        try {
            file=new File("WriteFile.txt");
            if(!file.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(file);
            fw.write("This is an string written to a file");
            fw.flush();
            fw.close();
            System.out.println("File written Succesfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 6
Author: Anurag Goel, 2014-11-20 10:29:10
package fileoperations;
import java.io.File;
import java.io.IOException;

public class SimpleFile {
    public static void main(String[] args) throws IOException {
        File file =new File("text.txt");
        file.createNewFile();
        System.out.println("File is created");
        FileWriter writer = new FileWriter(file);

        // Writes the content to the file
        writer.write("Enter the text that you want to write"); 
        writer.flush();
        writer.close();
        System.out.println("Data is entered into file");
    }
}
 6
Author: Suthan Srinivasan, 2015-07-20 12:01:03
 5
Author: Ran Adler, 2015-06-10 05:32:40

A maneira mais simples que consigo encontrar:

Path sampleOutputPath = Paths.get("/tmp/testfile")
try (BufferedWriter writer = Files.newBufferedWriter(sampleOutputPath)) {
    writer.write("Hello, world!");
}

Provavelmente só funcionará para 1, 7+.

 5
Author: qed, 2017-01-14 15:59:18

Se estamos usando Java 7 e acima e também sabemos o conteúdo a ser adicionado (adicionado) ao arquivo podemos fazer uso do método newbufferedwriter no Pacote NIO.

public static void main(String[] args) {
    Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
    String text = "\n Welcome to Java 8";

    //Writing to the file temp.txt
    try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        writer.write(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Há poucos pontos a registar:

  1. é sempre um bom hábito especificar codificação de codificação e para isso temos constante na classe StandardCharsets.
  2. o código usa try-with-resource a declaração em que os recursos são automaticamente fechados após a tentativa.

Embora a OP não tenha pedido, mas apenas em caso queiramos procurar por linhas com alguma palavra-chave específica por exemplo confidential podemos fazer uso de APIs stream em Java:

//Reading from the file the first line which contains word "confidential"
try {
    Stream<String> lines = Files.lines(FILE_PATH);
    Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
    if(containsJava.isPresent()){
        System.out.println(containsJava.get());
    }
} catch (IOException e) {
    e.printStackTrace();
}
 4
Author: i_am_zero, 2015-06-21 07:00:19

Leitura e escrita de Ficheiros com entrada e saída:

//Coded By Anurag Goel
//Reading And Writing Files
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class WriteAFile {
    public static void main(String args[]) {
        try {
            byte array [] = {'1','a','2','b','5'};
            OutputStream os = new FileOutputStream("test.txt");
            for(int x=0; x < array.length ; x++) {
                os.write( array[x] ); // Writes the bytes
            }
            os.close();

            InputStream is = new FileInputStream("test.txt");
            int size = is.available();

            for(int i=0; i< size; i++) {
                System.out.print((char)is.read() + " ");
            }
            is.close();
        } catch(IOException e) {
            System.out.print("Exception");
        }
    }
}
 4
Author: Anurag Goel, 2017-01-14 15:59:48

Apenas inclui este pacote:

java.nio.file

E então você pode usar este código para escrever o arquivo:

Path file = ...;
byte[] buf = ...;
Files.write(file, buf);
 4
Author: Arsalan Hussain, 2017-01-14 16:01:01
Vale a pena tentar o Java 7+:
 Files.write(Paths.get("./output.txt"), "Information string herer".getBytes());
Parece promissor...
 4
Author: Sherlock Smith, 2017-01-14 16:06:59

Para vários ficheiros pode usar:

static void out(String[] name, String[] content) {

    File path = new File(System.getProperty("user.dir") + File.separator + "OUT");

    for (File file : path.listFiles())
        if (!file.isDirectory())
            file.delete();
    path.mkdirs();

    File c;

    for (int i = 0; i != name.length; i++) {
        c = new File(path + File.separator + name[i] + ".txt");
        try {
            c.createNewFile();
            FileWriter fiWi = new FileWriter(c.getAbsoluteFile());
            BufferedWriter buWi = new BufferedWriter(fiWi);
            buWi.write(content[i]);
            buWi.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Está a funcionar muito bem.
 4
Author: Tobias Brohl, 2017-01-14 16:09:27

Aqui estão algumas das maneiras possíveis de criar e escrever um arquivo em Java:

Usar O 'FileOutputStream'

try {
  File fout = new File("myOutFile.txt");
  FileOutputStream fos = new FileOutputStream(fout);
  BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
  bw.write("Write somthing to the file ...");
  bw.newLine();
  bw.close();
} catch (FileNotFoundException e){
  // File was not found
  e.printStackTrace();
} catch (IOException e) {
  // Problem when writing to the file
  e.printStackTrace();
}

Usar O Texto Do Ficheiro

try {
  FileWriter fw = new FileWriter("myOutFile.txt");
  fw.write("Example of content");
  fw.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when writing to the file
  e.printStackTrace();
}

Utilizar A 'PrintWriter'

try {
  PrintWriter pw = new PrintWriter("myOutFile.txt");
  pw.write("Example of content");
  pw.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when writing to the file
  e.printStackTrace();
}

Utilizar OutputStreamWriter

try {
  File fout = new File("myOutFile.txt");
  FileOutputStream fos = new FileOutputStream(fout);
  OutputStreamWriter osw = new OutputStreamWriter(fos);
  osw.write("Soe content ...");
  osw.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when writing to the file
  e.printStackTrace();
}

Para mais informações, consulte este tutorial sobre como ler e escrever ficheiros em Java .

 4
Author: Mehdi, 2018-04-04 15:51:09

Existem algumas maneiras simples, como:

File file = new File("filename.txt");
PrintWriter pw = new PrintWriter(file);

pw.write("The world I'm coming");
pw.close();

String write = "Hello World!";

FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);

fw.write(write);

fw.close();
 3
Author: imvp, 2017-01-14 16:02:47

Pode até criar um ficheiro temporário usando uma propriedade do sistema , que será independente do SO que está a usar.

File file = new File(System.*getProperty*("java.io.tmpdir") +
                     System.*getProperty*("file.separator") +
                     "YourFileName.txt");
 3
Author: Muhammed Sayeed, 2017-01-14 16:07:52
Usando a biblioteca de goiaba do Google, podemos criar e escrever para um arquivo muito facilmente.
package com.zetcode.writetofileex;

import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;

public class WriteToFileEx {

    public static void main(String[] args) throws IOException {

        String fileName = "fruits.txt";
        File file = new File(fileName);

        String content = "banana, orange, lemon, apple, plum";

        Files.write(content.getBytes(), file);
    }
}

O exemplo cria um novo ficheiro fruits.txt no directório raiz do projecto.

 2
Author: Jan Bodnar, 2016-08-15 13:40:00

A ler a colecção com os clientes e a gravar para Ficheiro, com a JFilechooser.

private void writeFile(){

    JFileChooser fileChooser = new JFileChooser(this.PATH);
    int retValue = fileChooser.showDialog(this, "Save File");

    if (retValue == JFileChooser.APPROVE_OPTION){

        try (Writer fileWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileChooser.getSelectedFile())))){

            this.customers.forEach((c) ->{
                try{
                    fileWrite.append(c.toString()).append("\n");
                }
                catch (IOException ex){
                    ex.printStackTrace();
                }
            });
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}
 2
Author: hasskell, 2017-01-14 16:05:52

A melhor maneira é usar Java7: Java 7 introduz uma nova forma de trabalhar com o sistema de arquivos, juntamente com um novo utilitário class – Files. Usando a classe de arquivos, podemos criar, mover, copiar, excluir arquivos e diretórios também; ele também pode ser usado para ler e escrever para um arquivo.

public void saveDataInFile(String data) throws IOException {
    Path path = Paths.get(fileName);
    byte[] strToBytes = data.getBytes();

    Files.write(path, strToBytes);
}

Escrever com FileChannel Se você está lidando com arquivos grandes, FileChannel pode ser mais rápido do que o padrão IO. A seguinte sequência de código de escrita para um ficheiro que utiliza Filechanel:

public void saveDataInFile(String data) 
  throws IOException {
    RandomAccessFile stream = new RandomAccessFile(fileName, "rw");
    FileChannel channel = stream.getChannel();
    byte[] strBytes = data.getBytes();
    ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
    buffer.put(strBytes);
    buffer.flip();
    channel.write(buffer);
    stream.close();
    channel.close();
}

Gravar com o 'DataOutputStream'

public void saveDataInFile(String data) throws IOException {
    FileOutputStream fos = new FileOutputStream(fileName);
    DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
    outStream.writeUTF(data);
    outStream.close();
}

Escrever com o 'FileOutputStream'

Vamos agora ver como podemos usar o FileOutputStream para escrever dados binários em um arquivo. O seguinte código converte um texto int bytes e grava os bytes num ficheiro usando um fluxo de Ficheiros:
public void saveDataInFile(String data) throws IOException {
    FileOutputStream outputStream = new FileOutputStream(fileName);
    byte[] strToBytes = data.getBytes();
    outputStream.write(strToBytes);

    outputStream.close();
}

Escrever com o PrintWriter nós podemos usar um Impresswriter para escrever texto formatado em um arquivo:

public void saveDataInFile() throws IOException {
    FileWriter fileWriter = new FileWriter(fileName);
    PrintWriter printWriter = new PrintWriter(fileWriter);
    printWriter.print("Some String");
    printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
    printWriter.close();
}

Escrever com o 'BufferedWriter': usar 'BufferedWriter' para escrever um texto num ficheiro Novo:

public void saveDataInFile(String data) throws IOException {
    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
    writer.write(data);

    writer.close();
}

Adicione um texto ao ficheiro existente:

public void saveDataInFile(String data) throws IOException {
    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
    writer.append(' ');
    writer.append(data);

    writer.close();
}
 2
Author: sajad abbasi, 2018-06-22 13:41:11

No Java 8, use os ficheiros e caminhos e use a construção do 'try-with-resources'.

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class WriteFile{
    public static void main(String[] args) throws IOException {
        String file = "text.txt";
        System.out.println("Writing to file: " + file);
        // Files.newBufferedWriter() uses UTF-8 encoding by default
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(file))) {
            writer.write("Java\n");
            writer.write("Python\n");
            writer.write("Clojure\n");
            writer.write("Scala\n");
            writer.write("JavaScript\n");
        } // the file will be automatically closed
    }
}
 1
Author: praveenraj4ever, 2018-06-14 04:53:53