IO流之RandomAccessFile和File

通过学习一些经典案例来复习基础

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

RandomAccessFile类

含义和使用场景随机访问数据的一个类,可以跳转到任意位置来进行数据读写;

常用方法:          

        RandomAccessFile类为用户提供了两种构造方法:

        1、RandomAccessFile(File file, String mode)    // File指代文件,mode是指可以操作的状态,分别是r w  rw...表示读写;

        2、RandomAccessFile(String name, String mode) //name指代文件名

eg:

RandomAccessFile raf0 = new RandomAccessFile("D:/employee.txt", "rw");

       void close(): 关闭文件访问流,及其相关的系统资源;

       int read():在此文件中读取一个数据字节;

       int read(byte[] b): 按字节读取,并返回到字节数,若到末尾则返回-1;

       void seek(long pos): 重要,设置到此文件开头测量到的文件指针偏移量,在该位置发生下一个读取或写入操作;

       .........

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

public byte[] getBytes(Charset charset):使用给定的字符集的字节序列将此String解码,并将结果存储到一个新的字节数组。
eg:
package ts;

import java.io.UnsupportedEncodingException;

public class test2 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String s = "浣犲ソ"; //"你好"的gbk编码的字符串
        String ss = new String(s.getBytes("GBK"), "UTF-8");
        String sss = new String(s.getBytes("gbk"));
String s4=new String(s.getBytes("UTF-8")); System.out.println(ss); System.out.println(sss);
System.out.println(s4); } }
//对字符串按照 charsetName 进行编码(unicode→charsetName),返回编码后的字节。 //getBytes() 表示按照系统默认编码方式进行。

//
你好

//你好
//浣犲ソ

 数组扩容

              Arrays.copyOf(原始数组,数组的新长度);

package ts;
import java.util.Arrays;

public class test {
    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3, 4, 5};
        int[] arr2 = Arrays.copyOf(arr1, 5);
        int[] arr3 = Arrays.copyOf(arr1, 6);
        for(int i = 0; i < arr2.length; i++)
            System.out.print(arr2[i] + " ");
        System.out.println();
        for(int i = 0; i < arr3.length; i++)
            System.out.print(arr3[i] + " ");
    }
}

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

File类

常用api :创建文件、删除文件、判断、获取文件相关消息;

成年人的世界没有那么多的童话,也没有那么多的逆袭。
原文地址:https://www.cnblogs.com/shijinglu2018/p/11157265.html