BufferedWriter不写入文件

问题描述:

我必须从用户那里获取用户的名称和地址,并将其放入textfile中。我写下面的代码:

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.

您创建 BufferedWriter ,但从不 flush 关闭 它。

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

这些操作是实际写入文件的内容

These operations are what actually write to the file

正如@ManoDestra在评论中指出的那样,Java支持 try-with-resources 语句,它允许您格式化语句,如:

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))) {

由于 BufferedWriter 实现 AutoCloseable 界面,当 out code>尝试阻止退出

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