Himal Acharya Himal Acharya - 1 year ago 50
Java Question

BufferedWriter isnt writing to file

I have to take name and address of user from user and put it into textfile. I write following code:

package selfTest.nameAndAddress;

import com.intellij.codeInsight.template.postfix.templates.SoutPostfixTemplate;

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

* Created by
public class Test {
public static void main(String[] args) throws IOException {
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);

//creating addressbook text file
File fl=new File("E:/addressbook.txt");

FileReader fr=new FileReader(fl);
BufferedReader in=new BufferedReader(fr);

boolean eof=false;
int inChar=0;

String[] name=new String[2];
String[] address=new String[2];

int counter=0;

FileWriter fw=new FileWriter(fl);
BufferedWriter out=new BufferedWriter(fw);

System.out.println("Enter "+(counter+1)+" students name "+" and address");


System.out.println("Nmae: "+name[counter]+" ddress: "+address[counter]);

When I run the code, it takes input from user but the text file is empty. The address and name is not written into text file. How can I store the name and address into text file in the above code.

Answer Source

You create the BufferedWriter, but never flush or close it.

These operations are what actually write to the file

As @ManoDestra pointed out in the comments, Java supports the try-with-resources statement, which allows you to format your statements like:

try(BufferedWriter out = new BufferedWriter(new FileWriter(fl))) {

Since BufferedWriter implements the AutoCloseable interface, Java will automatically take care of cleanup of out when the try block exits