(一)使用标准数据流的应用程序 


标准数据流指在字符方式下(如DOS 提示符)程序与系统进行输入输出的方式,键盘和显示器屏幕是标准输入输出设备,数据输入的起点为键盘,数据输出的终点是屏幕,输出的数据可以在屏幕上显示出来。
1. 程序功能:将键盘上输入的字符在屏幕上显示出来

2. 编写KY10_1.java 程序文件,源代码如下。


class KY10_1{
public static void main(String[] args) throws java.io.IOException {
byte buffer[]=new byte[10];
System.out.println("从键盘输入不超过10 个字符,按回车键结束输入:");
int count =System.in.read(buffer);//读取输入的字符并存放在缓冲区buffer 中
System.out.println("保存在缓冲区buffer 中元素的个数为:"+count);
System.out.println("buffer 中各元素的值为:");
for (int i=0;i<count;i++){
System.out.print(" "+ buffer[i]);//在屏幕上显示buffer 元素的值
}
System.out.println();
System.out.println("输出buffer 字符元素:");
System.out.write(buffer, 0, buffer.length);
}

}

3. 编译、运行KY10_1.java 文件


(二)使用文件输入输出流的应用程序


1. 程序功能:将保存在本地机当前文件夹中的KY10_2.HTML 文本文件的内容在屏幕上显示出来,然后将其另存为KY10_2.txt 文件。
2. 编写KY10_2.java 程序文件,源代码如下
import java.io.*;
public class KY5_4 {
public static void main(String[] args) throws IOException {
FileReader in=new FileReader("KY5_1.HTML");//建立文件输入流
BufferedReader bin=new BufferedReader(in);//建立缓冲输入流
FileWriter out=new FileWriter(" KY5_1.txt",true);//建立文件输出流
String str;
while ((str=bin.readLine())!=null) {
//将缓冲区内容通过循环方式逐行赋值给字符串str
System.out.println(str);//在屏幕上显示字符串str
out.write(str+"\n");//将字符串str 通过输出流写入KY5_1.txt 中
}
in.close();
out.close();
}
}

3. 编译、运行程序


(三)转换流
1.程序功能:从键盘读入一行字符,并将其转换成大写打印在屏幕,当输入exit字符串时退出。
2. 编写KY10_3.java 程序文件,源代码如下
import java.io.*;
public class KY10_3 {
  public static void main(String args[]) {
    InputStreamReader isr = 
            new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);
    String s = null;
    try {
      s = br.readLine();
      while(s!=null){
        if(s.equalsIgnoreCase("exit")) break;
        System.out.println(s.toUpperCase());
        s = br.readLine();
      }
      br.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
3. 编译、运行程序

(四)使用数据输入输出流与文件输入输出流类的应用程序


使用数据输入流DataOutputStream 和数据输出流DataInputStream 可以读取或写入任何Java 类型的数据,不用关心它们的实际长度是多少字节。一般与文件输入流FileInputStream 和输出流类
FileOutputStream 一起使用。
1. 程序功能:将整型数据和字符串对象通过数据输出流写到文件中。将文件中的整型数据和字符串对象通过数据输出流读出,并在屏幕上显示文件中的内容。
2. 编写KY10_4.java 程序文件,源代码如下。
import java.io.*;
public class KY10_4
{
public static void main(String arg[])
{
try
{ //添加方式创建文件输出流
FileOutputStream fout = new FileOutputStream("KY5_6.txt",true);
DataOutputStream dout = new DataOutputStream(fout);
dout.writeInt(1);
dout.writeChars("罗马"+"\n");
dout.writeInt(2);
dout.writeChars("北京"+"\n");
dout.close();
}
catch (IOException ioe){}
try
{
FileInputStream fin = new FileInputStream("KY5_6.txt");
DataInputStream din = new DataInputStream(fin);
int i = din.readInt();
while (i!=-1) //输入流未结束时,输入流结束时i 为-1
{
System.out.print(i+" ");
char ch ;
while ((ch=din.readChar())!='\n') //字符串未结束时
System.out.print(ch);
System.out.println();
i = din.readInt();
}
din.close();
}
catch (IOException ioe){}
}
}
3. 编译并运行程序