JAVA中IO流 (读取键盘录入的详细讲解)以及InputStreamReader,OutputStreamWriter,setIn,setOut 讲解

本文详细介绍了JAVA中如何使用IO流进行键盘录入,包括初级录入、效率提升、使用InputStreamReader和OutputStreamWriter进行字符流转换。通过示例代码展示了readLine()方法的使用,并讲解了如何利用System的setIn和setOut改变标准输入输出设备,实现文件复制功能。
摘要由CSDN通过智能技术生成

java中键盘的录入

System.out: 对应的是标准输出设备,控制台
System.in: 对应的标准输入设备:键盘


初级录入

代码

import java.io.*;
public class ReadIn
{
    
	public static void main(String[] args)throws IOException
	{
    
		InputStream in=System.in;
		int by=in.read();
		System.out.println(by);
	}
}

结果

在这里插入图片描述

这里输出97是因为我们是Int 型


这时,我们多输出几个看看

代码

import java.io.*;
public class ReadIn
{
    
	public static void main(String[] args)throws IOException
	{
    
		InputStream in=System.in;
		int by1=in.read();
		int by2=in.read();
		int by3=in.read();
		System.out.println(by1);
		System.out.println(by2);
		System.out.println(by3);
	}
}

结果

在这里插入图片描述

上次我讲到 一个回车就是\r\n 这样子
而这里的13就是\r 10就是\n


上述的录入过于低效率,所以我们进行改进

需求
1.通过键盘录入数据
2.当录入一行数据后,就将该行数据进行打印
3.如果录入的数据是over,那么就停止录入

import java.io.*;
public class ReadIn
{
    
	public static void main(String[] args)throws IOException
	{
    
		InputStream in=System.in;
		int ch=0;
		while((ch=in.read())!=-1)
		{
    
			System.out.println(ch);
		}
	}
}


结果

在这里插入图片描述
此程序可以连续键盘写入,但是却不能停下来 ,需要用Ctrl +C 才可以退出


我们再次进行改进,一次性输出

import java.io.*;
public class ReadIn
{
    
	public static void main(String[] args)throws IOException
	{
    
		InputStream in=System.in;
		StringBuilder sb=new StringBuilder();
		
		while(true)
		{
    
			int ch=in.read();
			if(ch=='\r')
				continue
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值