FileWriter creates blank file

0

It is a very simple program, repeat what you write until you put it, and if you tell it to save, save everything you have written in a txt, the problem is that this txt always comes out blank and I do not know why since I have used the same way of saving files more times

import java.io.*;
import java.util.*;

public class Test
{
    public static void main(String[] args){
        try{
            FileWriter fw = new FileWriter("texto.txt");
            Scanner teclado = new Scanner(System.in);
            String texto = "";
            String aux;
            System.out.println("Teclee para para parar o guardar para guardar");
            do{
                aux = teclado.nextLine();
                switch(aux){
                    default:
                        System.out.println(aux);
                        texto += aux+"\r\n";
                        break;
                    case "guardar":
                        fw.write(texto);
                        System.out.println("Guardado");
                        break;
                    case "para":
                        break;
                }
            }while(!aux.equalsIgnoreCase("para"));
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}
    
asked by Adrian Rodríguez 07.06.2018 в 10:44
source

1 answer

2

The write() method only sends something to the writer to store it, but it does not write, so the file is blank. In order for the data to actually be written, you must invoke the method flush() of it.

And do not forget to do fw.close() at the end to close it.

import java.io.*;
import java.util.*;

public class Test
{
    public static void main(String[] args){
        try{
            FileWriter fw = new FileWriter("texto.txt");
            Scanner teclado = new Scanner(System.in);
            String texto = "";
            String aux;
            System.out.println("Teclee para para parar o guardar para guardar");
            do{
                aux = teclado.nextLine();
                switch(aux.toLowerCase()){
                    default:
                        System.out.println(aux);
                        texto += aux+"\r\n";
                        break;
                    case "guardar":
                        fw.write(texto);
                        fw.flush()
                        System.out.println("Guardado");
                        break;
                    case "para":
                        fw.close();
                        break;
                }
            }while(!aux.equalsIgnoreCase("para"));
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}
    
answered by 07.06.2018 / 10:48
source