<JAVA>字节流,字符流

 在程序中所有的数据都是以流的方式进行传输或者保存的,程序需要数据的时候需要使用输入流读取数据,而当程序需要将一些数据保存起来的时候,就要使用输出流。

  可以通过下面的输入输出流关系图表示这种方式。

字节流:

  字节流主要操作byte类型数据,以byte数组为准,主要操作类是OutputStream类和InputStream类。

其中OutputStream类是一个抽象类,如若要使用此类,首先就必须要通过子类来实例化对象。假设现在要操作的事一个文件,则可以使用FileOutputStream类,通过向上转型后,可以为OutputStream实例化,在OutputStream类中的主要操作方法如下:

1 public void close() throws IOException  //关闭输出流
2 public void flush() throws IOException  //刷新缓冲区
3 public void write(byte[] b) throws IOException //将一个byte数组写入数据流
4 public void write(byte[] b,int off,int len) throws IOException //将一个指定范围的byte数组写入数据流
5 public abstract void write(int b) throws IOException //将一个字节数据写入数据流

操作时必须接收File类实例,指明要输出的文件路径。

InputStream是一个输入流,也就是用来读取文件的流,抽象方法read读取下一个字节,当读取到文件的末尾时候返回 -1。如果流中没有数据read就会阻塞直至数据到来或者异常出现或者流关闭。这是一个受查异常,具体的调用者必须处理异常。除了一次读取一个字节,InputStream中还提供了read(byte[]),读取多个字节。read(byte[])其实默认调用的还是read(byte b[], int off, int len)方法,表示每读取一个字节就放在b[off++]中,总共读取len个字节,但是往往会出现流中字节数小于len,所以返回的是实际读取到的字节数。

public class Test_InputOrOutput {
    public static void main(String[] args) throws IOException{
            FileInputStream fin = new FileInputStream("hello.txt");
            byte[] buffer = new byte[1024];
            int x = fin.read(buffer,0,buffer.length);
            String str = new String(buffer);
            System.out.println(str);
            System.out.println(x);
            fin.close();
    }
}

以上为读取方法。

猜你喜欢

转载自www.cnblogs.com/lreing/p/9196616.html