我必须从用户那里获取用户的名称和地址,并将其放入文本文件中。我写以下代码:
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); } }
当我运行代码时,它需要用户输入,但文本文件为空。地址和名称未写入文本文件。如何在上面的代码中将名称和地址存储到文本文件中。
您创建的BufferedWriter,但从来没有flush或close它。
BufferedWriter
flush
close
这些操作是实际写入文件的操作
正如@ManoDestra在注释中指出的那样,Java支持try-with- resourcesstatement,它允许您将语句的格式设置为:
try-with- resources
try(BufferedWriter out = new BufferedWriter(new FileWriter(fl))) {
由于BufferedWriter实现了该AutoCloseable接口,因此Java将自动处理块退出out时的清理工作try
AutoCloseable
out
try