Showing posts with label filewriter. Show all posts
Showing posts with label filewriter. Show all posts

Java: quick way to read or write to file

Hi there,

Reading and writing to files in Java is very common use case. Sometimes you may not remember how to do it quickly and often need to search for it on google.

So here it is...

For file writing here comes FileWriter Java class. You can use constructor which takes either File or String as an argument. For example let say you want to create/write to a file named test.txt:

FileWriter writer = new FileWriter("test.txt"); // creates or overrides existing file
// or FileWriter writer = new FileWriter( new File("test.txt") );

writer.append("blah blah blah"); // append some text to the file
writer.append("\n"); // new line

// and at the end
writer.flush(); // flush the stream
writer.close();


Simple as that - file has been saved to your current working directory.

Now it's FileReader who reads data from files. For example:
FileReader fileReader = new FileReader(new File("test.txt"));

// now you may want to read line by line so here comes BufferedReader

BufferedReader br = new BufferedReader(fileReader);

String line = null;
// if no more lines the readLine() returns null
while ((line = br.readLine()) != null) {
     // reading lines until the end of the file

}

That's it. Simple stuff but worth of having it here to find quickly.

Cheers :)