Saturday, February 5, 2011

Store a text file in Java

When I started coding, I always searched for a simple way to save resluts from a Java application to a simple txt file. These days, I found it on a post-it behind my desk:

First of all, you need a java.io.File instance:
import java.io.File;
// ...
File file = new File („[file-path]file-name.file-extension“);
// ...
And here is the storage method:
import java.io.*;
//...
public static void save(File file) {
    try {

        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        writer.close();
    }
    catch (IOException e) {
        e.printStackTrace();
        System.out.println("Error on file saving.");
    }
}
//...