黑马程序员----键盘录入,以over为结束(黑马视频)

------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------

package src.com.itheima.zijieliu;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 * 读取键盘录入
 * System.out:对应的是标准输出设备,控制台
 * System.in:对应的是标准的输入设备:键盘.
 * @author SUN
 *
 *需求1:
 *通过键盘录入数据.
 *当录入一行数据后,就将该行数据进行打印.
 *如果录入的是over,那么就停止录入
 *
 *需求2:
 *想把键盘录入的数据保存到一个文件当中
 *源:键盘
 *目的:文件
 */
public class SystemInDemo {
  //第一种  需求一
 public static void main() throws IOException {
  InputStream in=System.in;
  StringBuffer sb=new StringBuffer();
  int ch=0;
  while(true){
   ch=in.read();
   if(ch=='\r')
    continue;
   if(ch=='\n')
   {
   String str=sb.toString();
   if("over".equals(str)){
    break;
   }
   System.out.println(str.toUpperCase());
   sb.delete(0,sb.length());
   }else{
    sb.append((char)ch);
   }
  }
 }
 
 //第二种  需求一
 public static void main2()throws IOException{
  //获取键盘录入对象
  InputStream in=System.in;
  //将字节流对象转换成字符流对象,使用转换流.InputStreamReader
  InputStreamReader isr=new InputStreamReader(in);
  //为了提高效率,将字符串进行缓冲技术高效操作.使用BufferedReader.  不用也不让用readerLine方法
  BufferedReader bufr=new BufferedReader(isr);
  String line=null;
  while((line=bufr.readLine())!=null){
   if("over".equals(line)){
    break;
   }
   System.out.println(line);
  }
  //别忘记了关闭
  bufr.close();
 }
 public static void xuqiu2(){
  BufferedReader bf=null;
  BufferedWriter fw=null;
  try {
   bf=new BufferedReader(new InputStreamReader(System.in));
   fw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("K:\\outPut.txt")));
   String str= null;
   while((str=bf.readLine())!=null){
    if(str.equals("over"))
     break;
    fw.write(str);
    fw.newLine();
    fw.flush();
    System.out.println(str);
   }
   
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   if(bf!=null)
    try {
     bf.close();
    } catch (IOException e) {
     throw new RuntimeException("输入流错误");
    }
     if(fw!=null)
   try {
    fw.close();
   } catch (IOException e) {
    throw new RuntimeException("输出流错误");
   }
  }
 }
 
 public static void main(String[] args) throws IOException {
  //main();
  //main2();
  xuqiu2();
 }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值