编程实现以下功能:
在屏幕上显示:输入姓名,然后将用户输人的姓名保存到文本文件中。重复进行,直到用户输入空字符串为止.
从控制台输入名称,并写入文件,不想输入时,直接回车就可以退出
public class Test {
public static void main(String[] args) {
String filePath = "D:/2222.txt";//输出内容的文件路径
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(filePath)), "UTF-8"));
scanIn(filePath,bw);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void scanIn(String filePath,BufferedWriter bw) {
Scanner sc = new Scanner(System.in);
System.out.println("从控制台输入:");
String s = sc.nextLine(); //读取字符串型输入
try {
if(bw != null) {
bw.write(s + "\r\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(!s.isEmpty()) {//判断输入的是否为空
scanIn(filePath,bw);
}
}
}