BufferedWriter isnt writing to file

谁都会走 提交于 2019-12-20 02:54:13

问题


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");
        fl.createNewFile();

        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;


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

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

            name[counter]=br.readLine();
            address[counter]=br.readLine();

            out.write(name[counter]);
            System.out.println("Nmae: "+name[counter]+" ddress: "+address[counter]);
            counter++;
        }while(counter<2);
    }
}

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.


回答1:


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




回答2:


A simpler alternative to BufferedWriter is PrintStream:

PrintStream printer = new PrintStream(new File("filepath"));
System.setOut(printer);

And then you can print whatever you want to the file, e.g.

printer.println(name[counter]);

And then close it at the end:

printer.close();


来源:https://stackoverflow.com/questions/38960866/bufferedwriter-isnt-writing-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!