我必須從用戶處取得用戶的姓名和地址,並將其放入文本文件中。我寫了以下代碼:BufferedWriter沒有寫入文件
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);
}
}
當我運行代碼時,它從用戶接收輸入,但文本文件爲空。地址和名稱不寫入文本文件。如何在上面的代碼中將名稱和地址存儲到文本文件中。
您需要關閉流。 –
我建議使用[try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)爲您的流,讀者,作者等設置塊,以確保一切關閉並適當地沖洗。 – ManoDestra