import java.io.*;publicclassKeyboardInput{publicstaticvoid main (String args[]){
String s;// Create a buffered reader to read// each line from the keyboard.
InputStreamReader ir =newInputStreamReader(System.in);
BufferedReader in =newBufferedReader(ir);//BufferReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Unix: Type ctrl-d or ctrl-c to exit."+"\nWindows: Type ctrl-z to exit");try{// Read each input line and echo it to the screen.//Throws: IOException - If an I/O error occurs
s = in.readLine();while( s != null ){
System.out.println("Read: "+ s);
s = in.readLine();}// Close the buffered reader.
in.close();}catch(IOException e){// Catch any IO exceptions.
e.printStackTrace();}}}
读取文件内容,使用BufferedReader
//首先import java.io.*import java.io.*;publicclassReadFile1{publicstaticvoid main (String [] args){// 文件读取
File file =newFile("D:/desktop/123.txt");//文件必须自己创建//都放在try中try{//将文件里的内容放在一个缓冲区in中
BufferedReader in =newBufferedReader(newFileReader(file));
String s;
s = in.readLine();//按行读取while(s != null){
System.out.println(s);
s = in.readLine();}//关闭缓存区,即关闭文件
in.close();}//未找到文件catch(FileNotFoundException e1){
System.out.println("Not found the file: "+ file);}//输入异常catch(IOException e2){
e2.getStackTrace();}}}
将内容输入至文本中
import java.io.*;//写入文件publicclassWriteFile{publicstaticvoid main (String args[]){//创建文件,文件写入时,文件可以不存在,会自动创建
File file =newFile("D:/desktop/1234.txt");try{//这里我还是初始化了一个缓冲区,将输入的内容缓存在里面
BufferedReader in =newBufferedReader(newInputStreamReader(System.in));//PrintWriter的参数为文件名,功能为文件写入
PrintWriter out =newPrintWriter(file);
System.out.println("当写完文件内容后,按CTRL z 保存退出!!!");
String s;
s = in.readLine();//逐行读取while(s != null){//将输入内容,输出至文本中,这里输出只要println
out.println(s);
s = in.readLine();}//这里两个文件都需要关闭,否则无法写入文件中
in.close();
out.close();}//输入异常终止catch(IOException e){
e.getStackTrace();}}}