精品计算机课件Java程序基础教程第讲Java中的字节流.pdf
文本预览下载声明
Java 语言程序设计
第十四讲 Java 中的字节流
主要内容
InputStream 和OutputStream
FileInputStream 和FileOutputStream
其他字节I/ O流
InputStream 和OutputStream
InputStream
抽象类,声明了输入流的最基本操作——读操作。
read 方法
public int read() throws IOException
从流中读一个字节,当流中没有数据可读时,返回值为-1
public int read(byte[] b) throws IOException
从流中读适合数组b 尺寸的字节,置于数组中
public void read(byte[] b,int off,int len) throws
IOException
读入len 个字节,从下标off 开始置入数组b
available 方法
public int available() throws IOException
返回流中的有效字节数。
skip 方法
public long skip(long n) throws IOException
close 方法
public abstract void close() throws IOException
例:利用InputStream 设计一回声程序,允许字符窗口进行输入,并对键盘
输入即刻输出。
Java 语言程序设计
import java.io.*;
class Echo1{
Echo1(InputStream in) throws Exception{
int b;
while((b = in.read()) != -1){
System.out.print((char)b);
}
in.close();
}
public static void main(String[] args) throws Exception{
new Echo1(System.in);
}
}
说明:在Windows 中,流的结束标志为Ctrl+Z。
OutputStream
抽象类,声明了输出流的最基本操作——写操作。
write 方法
public void write (int i) throws IOException
向流中写一个字节
public void write (byte[] b) throws IOException
向流写数组b
public void write (byte[] b,int off,int len) throws
IOException
向流写数组b 中的len 个元素:下标从off 到off+len-1
OutputStream 类的其他常用方法有:flush ()、close ()等,flush 的意义同
Writer 类的同名方法,close 总是关闭流。
例:阅读程序,分析其功能。
import java.io.*;
class Copy{
Cop
显示全部