-1
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class FileGenerator {

    /**
     * @param args
     */
    public static void main(String[] args) {

        File outputFile;
        BufferedReader reader;
        FileWriter fileWriter;

        try {
            outputFile  = new File("test.txt");
            outputFile.createNewFile();

            fileWriter = new FileWriter(outputFile, false);

            reader = new BufferedReader(new FileReader("template.txt"));

            StringBuilder sb = new StringBuilder();
            String line = reader.readLine();

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = reader.readLine();
            }

            String everything = sb.toString();
            fileWriter.write(everything);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {

        }
    }
}

The fileWriter creates test.txt but the string inside of test.txt is empty. i want it doesnt happen empty. by the way you may say "String everything" can be empty. But it isnt. When i try without reader txt i mean "String everything = "some text", it happens same. it happens empty

Ahmet
  • 314
  • 5
  • 15

2 Answers2

1

The file is empty because the contents of everything are smaller than the operating systems and / or Java's I/O buffers, and the program ends without properly closing the file.

When you write something to a file, and you need to ensure that it is written without closing the file already, call flush(). Whenever you open an I/O resource, close it using close() after use. close() implies flushing the buffers.

Java 7 provides try-with-resources for that, like this:

try (FileWriter writer = new FileWriter("foo.txt")) {
    writer.write("Hello, world!\n");
    writer.flush();
    // do more stuff with writer
 } // <- closes writer implicitly as part of the try-with-resources feature
Christian Hujer
  • 17,035
  • 5
  • 40
  • 47
0

As suggested in the comments, you need to do fileWriter.close() in order to close the output stream. If it is a buffered writer, then closing it not necessary as explained here.

Is it necessary to close a FileWriter, provided it is written through a BufferedWriter?

Community
  • 1
  • 1
Invisible Arrow
  • 4,625
  • 2
  • 23
  • 31