How to create and write txt file in java?

Asked

Viewed 267 times

-2

I would like to know how to create and write in txt file. The goal is to write in CSV standard, tried with Bufferedwriter and did not work...

import java.io.*;

public class PersistenciaComArquivoDeString
{

    public void salvaPessoas(ListaComArray<Pessoa> lista)
    {
        try
        {
            BufferedWriter saida = new BufferedWriter(new FileWriter("pessoa.txt"));
            Pessoa aux ;
            for(int i=0 ; i<lista.tamanho() ; i++)
            {
                aux = lista.get(i);
                saida.write(aux.getNome());
                saida.newLine();
                saida.write(aux.getEndereco());
                saida.newLine();
                // saida.write(String.valueOf(aux.getIdade()));
                // saida.newLine();
                
                saida.close();
                
            }
            
        }        
        catch(IOException e)
        {
        }
    }

}

Probably the problem is being in creating the file, someone can help me?

  • The close is inside the for, then the first iteration will already close the file. Also, there should be no comma between the information, instead of newLine?

1 answer

1

In the java.io package we have everything we need to work with reading and writing files.

Example 01 of file writing:

public class TesteEscritaDeArquivo_1 {
    public static void main(String[] args) throws IOException {
        
        //Fluxo de saida de um arquivo
        OutputStream os = new FileOutputStream("file1.txt"); // nome do arquivo que será escrito
        Writer wr = new OutputStreamWriter(os); // criação de um escritor
        BufferedWriter br = new BufferedWriter(wr); // adiciono a um escritor de buffer
        
        br.write("Vamos escrever nesse novo arquivo em Java! que legal hahaha!!!");
        br.newLine();
        br.newLine();
        br.write("Vamos escrever outra linha aqui embaixo hahaha!!!");
        br.close();
    }
}

The steps were:

1: we instantiate our data file through the Fileoutputstream

2: we instantiate our writer who receives in his builder the reference of the Outputstream

3: We instantiate our Buffer who will be able to write to the archive

4: the behaviors are described in the very name of the method, but I draw attention to that it is always necessary to close the resource we open and do this with the close-up();

The next ways are simple and more common to be seen in java.

public class TesteEscritaDeArquivo_2 {
    public static void main(String[] args) throws IOException {
        
        BufferedWriter br = new BufferedWriter(new FileWriter("file2"));
        
        br.write("Vamos escrever nesse novo arquivo em Java! que legal hahaha!!!");
        br.newLine();
        br.newLine();
        br.write("Vamos escrever outra linha aqui embaixo hahaha!!!");
        br.close();
    }
}

In this implementation we use the class Bufferedwriter who is in the java since version 1.1 to write the file.

in your builder we passed directly the Filewriter, you are using this option as you have not shown the other details about your implementation as for example other behaviors classes gets complicated.

public class TesteEscritaDeArquivo_3 {
    public static void main(String[] args) throws IOException {
        
        PrintStream ps = new PrintStream("file3.txt");
        
        ps.print("Vamos escrever nesse novo arquivo em Java! que legal hahaha!!!");
        ps.println();
        ps.println();
        ps.print("Vamos escrever outra linha aqui embaixo hahaha!!!");
        ps.close();
    }
}

In this case we use the Printstream that appeared in java 1.5 and in this case we directly pass the name of the file in its constructor.

public class TesteEscritaDeArquivo_4 {
    public static void main(String[] args) throws IOException {
        
        PrintWriter ps = new PrintWriter("file3.txt");
        
        ps.print("Vamos escrever nesse novo arquivo em Java! que legal hahaha!!!");
        ps.println();
        ps.println();
        ps.print("Vamos escrever outra linha aqui embaixo hahaha!!!!!!!!");
        ps.close();
    }
}

In this case we use the Printwriter class.

Still to read files we have several options too,you can among others use the Scanner class passing the file inside the constructor.

Scanner scanner = new Scanner(new File("contas.csv"));

Java writing and reading classes have exceptions of the type Checked ie you are obliged to treat them in some way, I put these exceptions in the main only as a test, in a real scenario it would be more appropriate to put within the behavior of the class that is implementing it.

Make the most of your java.io is worth it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.