java 一个简单的编程 自键盘读入用户所输入的信息,并存入一个文件中,用户输入end后结束

如题所述

第1个回答  推荐于2017-12-15
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;

public class test {
public static void main(String[] arg) {
// 实例化扫描对像,用法看jdk中的API文档
Scanner sc = new Scanner(System.in);
// 实例化缓冲区用于存输入数据
StringBuffer sbf = new StringBuffer();
// 如果用户输入数据
while (sc.hasNext()) {
// 得到输入数据
String input = sc.next();
//如果用户输入'end'则结束
if(input.equals("end")){
break;
}
// 保存到缓冲区中
sbf.append(input);
try {
// 定义存储数据的文件
File file = new File("d:\\mao.txt");
// 定义文件写入流
FileWriter fw = new FileWriter(file);
// 将输入信息写入文件
fw.write(sbf.toString());
// 关闭文件流
fw.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}本回答被提问者采纳
第2个回答  2010-06-22
public static void main(String[] args) {

// ××××××××××××××××读入内容×××××××××××××××××
//新建一个用于读的对象,具体使用方式请参考API,下同
Scanner scanner = new Scanner(System.in);
//创建一个用于存储读入内容的字符串缓冲对象
StringBuilder sb = new StringBuilder();
//判断是否有新的输入
while(scanner.hasNext()) {
//读出新的输入
String next = scanner.next();
//判断为end时推出
if(next.equalsIgnoreCase("end"))
break;
//缓冲区中追加新读入内容
sb.append(next);
}

// ××××××××××××××××写入文件×××××××××××××××××
try {
//创建一个指向特定文件的带缓冲的输出对象
BufferedWriter bw = new BufferedWriter(new FileWriter("c:\\test.txt"));
//将缓冲区中内容写入到输出对象中
bw.write(sb.toString());
//将所有缓冲在输出对象中的内容写入到文件
bw.flush();
//关闭文件写对象,避免泄漏
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
相似回答