您的位置:首页 > 编程语言 > Java开发

Java.关于IO代码复用

2010-12-31 10:40 351 查看
重视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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: