(三十九)、RandomAccess,对象流,数据流

来源:互联网 发布:诚信大数据 编辑:程序博客网 时间:2024/06/07 05:16

RandomAccess类

RandomAccessFile类可以说是Java语言中功能最为丰富的文件访问类,它提供了众多的文件访问方法。RandomAccessFile类支持“随机访问”方式,可以跳转到文件的任意位置处读写数据。在要访问一个文件的时候,不想把文件从头读到尾,而是希望像访问一个数据库一样地访问一个文本文件,这时,使用RandomAccessFile类就是最佳选择。
RandomAccessFile对象类有个位置指示器,指向当前读写处的位置,当读写n个字节后,文件指示器将指向这n个字节后的下一个字节处。刚打开文件时,文件指示器指向文件的开头处,可以移动文件指示器到新的位置,随后的读写操作将从新的位置开始。RandomAccessFile在数据等长记录格式文件的随机(相对顺序而言)读取时有很大的优势,但该类仅限于操作文件,不能访问其它的IO 设备,如网络、内存映像等。

RandomAccessFile类的构造方法:new RandomAccessFile(f, "rw");  // 读写方式new RandomAccessFile(f, "r");       // 只读方式

以读写的方式打开一个文件时,如果文件不存在,程序会自动创建此文件。
有关RandomAccessFile类中的成员方法及使用说明请参阅JDK文档。常见API如下:

•void close():关闭此随机访问文件流并释放与该流关联的所有系统资源。•long getFilePointer():返回此文件中的当前偏移量。•long length():返回此文件的长度。•read函数集:从文件读•void seek(long pos):设置到此文件开头测量到的文件指针偏移量,在该位置发生下一个读取或写入操作。•void setLength(long newLength):设置此文件的长度。•int skipBytes(int n):尝试跳过输入的 n 个字节以丢弃跳过的字节。•write函数集:往文件写

RandomAccessFileDemo.java

public class RandomAccessFileDemo {    public static void main(String[] args) throws IOException {        RandomAccessFile raf = new RandomAccessFile("c:/a.txt", "rw");        System.out.println((char) raf.read());        System.out.println((char) raf.read());        System.out.println((char) raf.read());        System.out.println((char) raf.read());        long filePointer = raf.getFilePointer();        System.out.println(filePointer);// 获取文件指针        raf.seek(0);// 移动指针到指定位置        raf.write(54);        System.out.println((char) raf.read());        System.out.println((char) raf.read());        raf.setLength(1024 * 2048 * 256);// 设置文件长度        raf.close();    }}

实现文件断点续传

/* 断点续传: 第一次下载  100    第二次下次  101  想办法知道上次从哪个地方断掉的。  上次已经下载到了什么位置。  记下断点的位置 需要一个第三方的文件来专门的记录断点位置 */public class CopyFileDemo {    public static void main(String[] args) {        File srcFile = new File("F:/img.png");        File desDir = new File("c:/");        copyFileToDir(srcFile, desDir);    }    /**     * 把指定的文件copy到指定的目录中     *      * @param srcFile     *            指定的文件     * @param desDir     *            指定的目录     */    public static void copyFileToDir(File srcFile, File desDir) {        desDir.mkdirs();        File configFile = new File(desDir, srcFile.getName() + ".config"); // aa.avi.config        File desFile = new File(desDir, srcFile.getName()); // 目标文件        if (!configFile.exists() && desFile.exists()) { // 如果配置文件不存在,则证明曾经下载过,而且还下载完了            return;        }        try (RandomAccessFile rafSrc = new RandomAccessFile(srcFile, "r");                RandomAccessFile rafDes = new RandomAccessFile(desFile, "rw");                RandomAccessFile rafConfig = new RandomAccessFile(configFile,                        "rw")) {            rafDes.setLength(srcFile.length()); // 让文件与源文件的长度保持一致            rafConfig.setLength(8); // 让配置的文件长度为8个字节            rafConfig.seek(0);            // 每次复制的开始,必须把源文件的指针和目标文件的指针从上次断开的位置去读            long pointer = rafConfig.readLong();            rafSrc.seek(pointer);            rafDes.seek(pointer);            byte[] buff = new byte[256];            int len = -1;            while ((len = rafSrc.read(buff)) != -1) {                rafDes.write(buff, 0, len);                // 每复制一次之后,赶紧记录下指针的位置,以备断点续传来用                pointer = rafSrc.getFilePointer();                rafConfig.seek(0); // 在对配置文件写的时候,每次先让指针移动到最初的位置                rafConfig.writeLong(pointer);            }        } catch (Exception e) {            e.printStackTrace();        }        configFile.delete();    }}

对象流

用来存对象的流

先建一个User对象
Serializable 表示该对象可序列化

public class User implements Serializable {    private String name;    private int age;    transient private String pwd;    public User(String name, int age, String pwd) {        super();        this.name = name;        this.age = age;        this.pwd = pwd;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public String getPwd() {        return pwd;    }    public void setPwd(String pwd) {        this.pwd = pwd;    }    @Override    public String toString() {        return "User [name=" + name + ", age=" + age + ", pwd=" + pwd + "]";    }}

存对象

public class ObjectOutputStringDemo {    public static void main(String[] args) throws FileNotFoundException,            IOException {        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(                "c:/a.obj"));        oos.writeObject(new User("小明", 21, "qwert"));        oos.writeObject(new User("小红", 20, "12345"));        oos.writeObject(new User("小绿", 21, "54321"));        oos.writeObject("abcd");        oos.close();    }}

取出对象

读的顺序要和存的顺序一致

public class ObjectInputStreamDemo {    public static void main(String[] args) throws FileNotFoundException,            IOException, ClassNotFoundException {        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(                "c:/a.obj"));        User user = (User) ois.readObject();        User user1 = (User) ois.readObject();        User user2 = (User) ois.readObject();        String s = (String) ois.readObject();        System.out.println(user);        System.out.println(user1);        System.out.println(user2);        System.out.println(s);        ois.close();    }}

数据流

从底层输入流中读取基本数据类型

  • DataOutputStream
public class DataOutputStreamDemo {    public static void main(String[] args) throws IOException {        DataOutputStream dos = new DataOutputStream(new FileOutputStream(                "c:/datas.data"));        dos.writeInt(200);        dos.writeBoolean(true);        dos.close();    }}
  • DataInputStream
public class DataInputStreamDemo {    public static void main(String[] args) throws IOException {        DataInputStream dis = new DataInputStream(new FileInputStream(                "c:/datas.data"));        System.out.println(dis.readInt());        System.out.println(dis.readBoolean());        dis.close();    }}
0 0
原创粉丝点击