Java从命令行读取输入然后输出到文本文件的问题
importjava.io.*;publicclassInputName{publicstaticvoidmain(String[]args)throwsIOExcept...
import java.io.*;
public class InputName {
public static void main (String [] args)throws IOException{
System.out.println("请输入姓名(结束请敲两次回车键):");//提示语
InputStreamReader keyBoard = new InputStreamReader(System.in);//读入用户输入,并将其转换为字符流
BufferedReader br = new BufferedReader(keyBoard);//建立输入缓冲区
File f = new File("name.txt");//创建name.txt文件
f.createNewFile();//若该文件原来不存在,则新建文件
FileWriter writer = new FileWriter(f,true);//新建输出器
String s;//用作输出的临时字符串
while((s=br.readLine())!=""){
writer.write(s);
}
writer.close();
keyBoard.close();
br.close();
}
}
请问为什么没法输出到name.txt? 展开
public class InputName {
public static void main (String [] args)throws IOException{
System.out.println("请输入姓名(结束请敲两次回车键):");//提示语
InputStreamReader keyBoard = new InputStreamReader(System.in);//读入用户输入,并将其转换为字符流
BufferedReader br = new BufferedReader(keyBoard);//建立输入缓冲区
File f = new File("name.txt");//创建name.txt文件
f.createNewFile();//若该文件原来不存在,则新建文件
FileWriter writer = new FileWriter(f,true);//新建输出器
String s;//用作输出的临时字符串
while((s=br.readLine())!=""){
writer.write(s);
}
writer.close();
keyBoard.close();
br.close();
}
}
请问为什么没法输出到name.txt? 展开
展开全部
import java.io.*;
public class InputName {
public static void main(String[] args) throws IOException {
System.out.println("请输入姓名(结束请敲两次回车键):");
InputStreamReader keyBoard = new InputStreamReader(System. in );
BufferedReader br = new BufferedReader(keyBoard);
FileWriter writer = new FileWriter("name.txt", true);
String s;
while ((s = br.readLine()) != null) {
writer.write(s);
}
writer.flush();
writer.close();
keyBoard.close();
br.close();
}
}
追问
我试过了,还是没法输出到文件呀?
追答
import java.io.*;
public class InputName {
public static void main(String[] args) throws IOException {
System.out.println("请输入姓名 :");
InputStreamReader keyBoard = new InputStreamReader(System. in );
BufferedReader br = new BufferedReader(keyBoard);
FileWriter writer = new FileWriter("name.txt", true);
String s;
while (true) {
s = br.readLine();
if (!"".equals(s)) {
writer.write(s);
writer.flush();
} else {
writer.close();
keyBoard.close();
br.close();
break;
}
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询