Java基础学习总结:IO之(六)RandomAccessFile类、Properties类

一、RandomAccessFile类

(1)简介和作用

RandomAccessFile是用来访问那些保存数据记录的文件的,你就可以用seek( )方法来访问记录,并进行读写了。这些记录的大小不必相同;但是其大小和位置必须是可知的。但是该类仅限于操作文件。

(2)继承关系

java.lang.Object
|____java.io.RandomAccessFile

RandomAccessFile类直接继承Object类,并不属于InputStream和OutputStream框架中的, 由于RandomAccessFile操作文件使用特殊的随机访问的特点,RandomAccessFile类不使用InputStream和OutputStream框架中的现有的方法,是一个独立的类。

(3)类声明

public class RandomAccessFile implements DataOutput, DataInput, Closeable {}

RandomAccessFile 类不但实现了 Closeable 接口,还同时实现了 DataOutput 、DataInput接口,所以RandomAccessFile类不像大多数文件类那样成对出现,它有自己的读和写的方法。

(4)构造方法

    public RandomAccessFile(String name, String mode)
        throws FileNotFoundException
    {
        this(name != null ? new File(name) : null, mode);
    }


    public RandomAccessFile(File file, String mode)
        throws FileNotFoundException
    {
        String name = (file != null ? file.getPath() : null);
        int imode = -1;
        if (mode.equals("r"))
            imode = O_RDONLY;
        else if (mode.startsWith("rw")) {
            imode = O_RDWR;
            rw = true;
            if (mode.length() > 2) {
                if (mode.equals("rws"))
                    imode |= O_SYNC;
                else if (mode.equals("rwd"))
                    imode |= O_DSYNC;
                else
                    imode = -1;
            }
        }
        if (imode < 0)
            throw new IllegalArgumentException("Illegal mode \"" + mode
                                               + "\" must be one of "
                                               + "\"r\", \"rw\", \"rws\","
                                               + " or \"rwd\"");
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkRead(name);
            if (rw) {
                security.checkWrite(name);
            }
        }
        if (name == null) {
            throw new NullPointerException();
        }
        if (file.isInvalid()) {
            throw new FileNotFoundException("Invalid file path");
        }
        fd = new FileDescriptor();
        fd.attach(this);
        path = name;
        open(name, imode);
    }

该类有两个构造方法,一个接受一个String类型的文件名和模式,一个接受一个File类型的对象和模式 ,没有无参构造。

含义

“r”以只读的方式打开。调用结果对象的任何write方法都将抛出IOException。
"rw"打开以便读取和写入。如果该文件尚不存在,则尝试创建该文件。
"rws"打开以便读取和写入,对于 "rw",还要求对文件的内容或元数据的每个更新都同步写入到底层存储设备。
"rwd"  打开以便读取和写入,对于 "rw",还要求对文件内容的每个更新都同步写入到底层存储设备。

(5)简单使用

RandomAccessFile的工作方式是,把 DataInputStream 和 DataOutputStream 结合起来,再加上它自己的一些特有的方法,比如定位用的getFilePointer( ),在文件里移动的偏移量用的seek( ),以及判断文件大小的length( )、skipBytes()跳过多少字节数等。

package basis.StuIO.RandomAccessFile;

import java.io.RandomAccessFile;

public class StuRandomAccF {
    public static void main(String[] args) throws Exception{
        RandomAccessFile raf = new RandomAccessFile("test.txt","rw");

        //向文件写数据
        raf.writeInt(20);//int,4 字节
        raf.writeDouble(3.1415);//doublie, 8 字节
        raf.writeUTF("这是一个UTF字符串");

        raf.writeBoolean(true);//boolean , 1字节
        raf.writeFloat(3.14f);// float , 4 字节

        raf.writeShort(355);// sort , 2 字节

        raf.writeUTF("又是一个UTF字符串");
        raf.writeChar('a');// char , 2 字节
        raf.writeLong(12345678);//long , 8 字节
        //设置文件指针偏移量
        //把文件指针位置设置到文件起始处
        raf.seek(0);

        //读数据,注意文件指针的位置
        System.out.println("——————从file文件指定位置读数据——————");
        System.out.println(raf.readInt());
        System.out.println(raf.readDouble());
        System.out.println(raf.readUTF());
        //跳过指定的字节长度
        raf.skipBytes(5);//跳过5个字节,即本例中的boolean 和 float
        System.out.println(raf.readShort());

        System.out.println("——————文件复制(从file到fileCopy)——————");
        raf.seek(0);
        RandomAccessFile fileCopy = new RandomAccessFile("fileCopy.txt", "rw");
        int len = (int) raf.length();// 取得文件长度(字节数)
        byte[] b = new byte[len];
        // 全部读取
        raf.readFully(b);
        fileCopy.write(b);
        System.out.println("复制完成!");
    }
}

RandomAccessFile的绝大多数功能,但不是全部,已经被JDK 1.4的 NIO 的"内存映射文件(memory-mapped files)"给取代了,你该考虑一下是不是用"内存映射文件"来代替RandomAccessFile了。 

NIO:

NIO即New IO,这个库是在JDK1.4中才引入的。NIO和IO有相同的作用和目的,但实现方式不同,NIO主要用到的是块,所以NIO的效率要比IO高很多。在Java API中提供了两套NIO,一套是针对标准输入输出NIO,另一套就是网络编程NIO。NIO的详细介绍和使用会在后续文章中讨论。

二、Properties类

参考菜鸟教程:https://www.runoob.com/java/java-properties-class.html

(1)properties类

  1. Properties 继承于 Hashtable,表示一个持久的属性集。属性列表中每个键及其对应值都是一个字符串。
  2. Properties 类被许多Java类使用。例如,在获取环境变量时它就作为System.getProperties()方法的返回值。

(2)继承关系

java.lang.Object
|____java.util.Dictionary<K,V>
     |____java.util.Hashtable<Object,Object>
          |___java.util.Properties

(3)类声明

public class Properties extends Hashtable<Object,Object> {

    private static final long serialVersionUID = 4112578634029874840L;

    protected Properties defaults;
}

Properties ;类是 HashTable 的子类,实现了 Serializable 接口。该类中有一个默认的 Properties 类对象,初始值为null。

(4)构造方法

public Properties() {
    this(null);
}

public Properties(Properties defaults) {
    this.defaults = defaults;
}

 Properties 有两个构造方法,一个没有默认值,一个有默认值。

(6)除了从Hashtable中所定义的方法,Properties定义了以下方法:

方法 
String getProperty(String key)获取指定key的value值
String getProperty(String key, String defaultProperty)获取指定key的value值
void list(PrintStream streamOut)将属性列表输出到指定的输出流
void list(PrintWriter streamOut)将属性列表输出到指定的输出流
void load(InputStream streamIn) throws IOException加载:从输入流中读取属性列表(键和元素对)。
Object setProperty(String key, String value)添加属性(key-value对)
void store(OutputStream streamOut, String description)将属性集合写入到文件

(5)简单使用

1)把Properties 属性列表写入文件: store()

package basis.StuIO.StuProperties;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

public class StuProperties {
    public static void main(String[] args) throws IOException {
        //创建对象
        Properties properties = new Properties();
        //添加属性
        properties.setProperty("name","suxing");
        properties.setProperty("age","21");
        properties.setProperty("phone","111111");

        //properties.put(123,457);

        properties.store(new FileWriter("suxing.properties"),"info");
        properties.list(System.out);
    }
}

会在项目根目录中生成一个suxing.properties 文件,打开文件:

#info
#Sat Aug 10 12:06:16 CST 2019
phone=111111
age=21
name=suxing

注意:

由于Properties 类继承自 HashTable 类,所以,该类对象可以使用 HashTable的put() 方法向Properties 中添加属性键值对:

properties.put("email","11111@qq.com");

但是,你最好不要这么用,因为Properties中存储的都是String 类型的键值对,而put() 方法的参数是Object 类型的,也就是说你可以向Properties 中添加任意类型的键值对,添加时会出现 ClassCastException 异常。

2)读取 suxing.properties 文件:load()

使用Properties中的load()方法,可以将输出流中的属性读取到Properties对象中。

package basis.StuIO.StuProperties;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

public class loadProperties {
    public static void main(String[] args) throws Exception{
        Properties properties = new Properties();
        //从输入流中读取属性列表(键和元素对)。
        properties.load(new BufferedInputStream(new FileInputStream(new File("suxing.properties"))));
        System.out.println(properties);
    }
}

3)将属性列表输出到制定输出流:list()

读取文件的属性列表,使用list()方法打印到控制台:

Properties properties = new Properties();
//从输入流中读取属性列表(键和元素对)。
properties.load(new BufferedInputStream(new FileInputStream(new File("suxing.properties"))));

//将属性列表输出到标准输出流,打印到控制台
properties.list(System.out);

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值