102java字节流与字符流(字节输入流:InputStream)

71 阅读2分钟

字节流与字符流(字节输入流:InputStream)

 


字节流与字符流(字节输入流:InputStream)的使用

利用OutputStream实现了程序输出内容到文件的处

理,那么下面就需要通过程序,读取文件内容那么就要使用到InputStream类,

 

这个类的定义如下:

Public abstract class Inputstream

extends Object

implements Closeable 

 

发现Inputstream类只实现了closeable接口,在Inputstream类里面提供有如下方法

  • 读取数据到字节数组中:

public int read (byte[] b) throws IOException;

|-返回读取数据的读取个数;如果此时开辟的字节数组的大小大于了我们读取的数据大小,则返回的就是读取个数;

|-如果现在要读取的数据大于数组的内容,那么这个时候返回的就是数组的长度;

|-如果没有数据了还要继续读,那么就返回-1;

 

  • 读取部分数据到字节数组之中:

public int read(byte[] b ,int off ,int len)throws IOEception

|-每次只读取传递数组的部分内容,如果读取满了,则返回的就是长度(len),如果没有读取满,那么返回的就是读取的数据个数,如果读取到最后没有数据了,返回的就是-1;

 

  • 读取单个字节:

public abstract int read() throws IOEception

|-每次读取一个字节内容,读取没有数据了,返回为-1.

 

InputStream类是一个抽象类,如果要对文件进行处理则肯定使用FileInputStream类完成;

 

 

 

范例:实现文件信息的读取

public class TestDempublic static void main(stritg[] args) throws ExceptionFile file s new File

("d: File separator +"hello. txt");if(fie, exists()

//保证程序存在才可以进行读取处理

Inputstream input= new FileInputstream(file)I byte datal= new byte[1024】;

∥每次可以取的量大量int1en= input.read(data);

/此时的数据读取了数之中System,Out,println

(”读取内容【"+ new string(data,θ.1m)input.close();

 

整个操作流程可以发现OutputStream, InputStream类的使用形式上是非常类似的。