Java.关于IO代码复用

本文探讨了Java中如何利用IO流进行高效的数据读写,并通过代码复用提高程序的灵活性与可维护性。文章重点介绍了如何使用System.in和System.out进行数据交互,以及如何通过函数封装读取流程来应对不同输入源。

重视IO程序代码的复用 System.in是连接到键盘的,是InputStream类型的实例对象。System.out连接到显示器,是PrintStream类的实例对象。 不管各种底层物理设备用什么方式实现数据的终止点,InputStream的read方法总是返回-1来表示输入流的结束 在windows下,按下Ctrl+Z组合键可以产生键盘输入流的结束标记,在linux下则是按下Ctrl+D组合键来产生键盘输入流的结束标记。 要编程从键盘上连续读取一大段数据时,应尽量将读取数据的过程放在函数中完成,使用-1来作为键盘输入的结束点。在改函数中编写的程序不应直接使用System.in读取数据,而是用一个InputStream类型的形式参数对象来读取数据,然后将System.in作为实参传递给InputStream类型的形式参数来调用该函数。 用基类类型的对象作为形参,然后传递子类类型对象来使用,以不变应万变。提高服用性

import java.io.*; class ByteArrayTest { public static void main(String[] args) { // TODO: Add your code here /* String tmp="abcdefjklmnopqrst"; byte [] src=tmp.getBytes(); ByteArrayInputStream input=new ByteArrayInputStream(src); ByteArrayOutputStream output=new ByteArrayOutputStream();//这里不用传递字节数组,ByteArrayOutputStream会自动创建一个32字节的缓冲区用来写入数据"Creates a new byte array output stream." transform(input,output); byte[] result=output.toByteArray(); //public byte[] toByteArray() "Creates a newly allocated byte array. Its size is the current size of this output stream and the valid contents of the buffer have been copied into it." System.out.println(new String(result)); */ transform(System.in,System.out); } public static void transform(InputStream in,OutputStream out){ int ch=0; try{ while((ch=in.read())!=-1){ int upperCh=/*(int)*/Character.toUpperCase((char)ch); //char表示的范围比int小 out.write(upperCh); } }catch(Exception e){ e.printStackTrace(); } } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值