文章标题

来源:互联网 发布:光电效应 知乎 编辑:程序博客网 时间:2024/06/08 11:55

一、字节流

二、Printwriter

三、合并流

四、切割流

五、对象的序列化

六、管道流

七、随机读写

IO包中的RandomAccessFile

RandomAccessFile,直接继承自Object,即支持读,也支持写。对象内部封装了字节输入流和字节输出流,和字节数据,可以操作指针。获取数组元素,写入数组元素。

类的声明

public class RandomAccessFileextends Objectimplements DataOutput, DataInput, Closeable

继承了DataOutput,DataInput具有读写基本数据类型的功能。

常用API

getFilePointer:获取数据
seek设置数据

构造方法

该类的构造方法,只能传入文件、或是文件路径,所以该类只能操作文件。并且没有空的构造方法。

RandomAccessFile(File file, String mode) RandomAccessFile(String name, String mode) ---------mode的值"r":只读"rw":读写"rws""rwd"

方法说明

这个类的方法可以分为几类
读、读基本数据类型、设置、获取指针、写、其他(这里只是做简要介绍,具体请查看官档)

readBoolean()readByte() readChar() readDouble() readFloat() readInt()  readLong() readShort() readUnsignedShort() readUnsignedByte() 
read(byte[] b) read(byte[] b, int off, int len) 
readLine() readFully(byte[] b) readUTF() 
seek(long pos) getFilePointer() 
FileChannel getChannel() FileDescriptor  getFD() 
package cn.iktz.io.test;import java.io.IOException;import java.io.RandomAccessFile;/*文件的随机读写1、内部封装了一个数组,而且通过指针对数组的元素进行操作。2、可以通过getFilePointer获取指针位置,可以通过seek改变指针的位置。*/public class RandomAccessFileDemo {    public static void main(String[] args) throws IOException {         writeFile();         readFile();    }    //    public static void readFile() throws IOException {        RandomAccessFile raf = new RandomAccessFile("e:\\t.txt", "r");        // 调整对象中指针。         raf.seek(8*1);        // 跳过指定的字节数        //raf.skipBytes(8);        /*读取一个字 start*/        byte[] buf = new byte[4];        raf.read(buf);        System.out.println(new String(buf));        /*读取一个字 end*/        raf.close();    }    public static void writeFile() throws IOException {        RandomAccessFile raf = new RandomAccessFile("e:\\t.txt", "rw");        raf.seek(8 * 1);//把指针移到第八个字节的位置        raf.write("iktz.cn".getBytes());        raf.close();    }}

八、操作基本类型的流对象DataStream

九、ByteArrayStream

ByteArrayStream使用的比较广泛。它相当于一个可变数组
通常,我们在操作字节流的时候,需要手动创建一个字节数组,并指定长度:byte buf = new byte[1024],见下面的代码。

    public void run() {        InputStream in = null;        FileOutputStream fos = null;        try {            in = socket.getInputStream();            fos = new FileOutputStream(new File("filePath"));            byte[] buf = new byte[1024];            int len = 0;            while ((len = in.read()) != -1) {                fos.write(buf, 0, len);            }        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                if (fos != null) {                    fos.close();                }                if (socket != null) {                    socket.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }    }

这里可以使用ByteArrayStream,两者的区别如下。
这里写图片描述

十、转换流的字符编码

0 0
原创粉丝点击