Java怎么从键盘输入数据直接到文件中

如题所述

第1个回答  2010-04-12
从键盘读取,任何把读取到的数据写入文件
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class Temp1 {
private static BufferedReader br;
private static PrintWriter pw;

public static void main(String[] args) {
try {
pw = new PrintWriter(new FileOutputStream("f:/test.txt", true));
br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("请输入:");
String temp = br.readLine();
if (temp.matches("bye")) {
System.out.println("系统退出!");
break;
}
if (temp == null) {
System.out.println("不能为null值!");
}
pw.write(temp);
pw.flush();
System.out.println("写入文件成功!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
pw.close();
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
}
第2个回答  2010-04-12
import java.io.FileWriter;

import java.util.Scanner;

public class NewTxt {

public static void main(String[] args) throws IOException {

Scanner s = new Scanner(System.in);

System.out.println("please enter ....(Quit-退出)");

String str;
FileWriter out = new FileWriter("d:\\test.txt");
do{
str = s.nextLine();
out.write(str+"\r\n");
}while(!"Quit".equalsIgnoreCase(str));
out.close();
}
}本回答被网友采纳
相似回答