java学习笔记#4-File

编码浅析

编码格式实例

文本文件就是字符序列,它可以是任意编码,中文机器上创建文本文件时,默认ansi编码。
不同的编码格式下输出存在差异:
将同一个字符串以不同编码格式读取,然后输出。

        String string1 = "测试12AB";
        byte[] bytes = new byte[0];
        byte[] bytes2 = new byte[0];
        byte[] bytes3 = new byte[0];
        try {
            bytes = string1.getBytes("utf-8");
            bytes2 = string1.getBytes("gbk");
            bytes3 = string1.getBytes("utf-16be");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        System.out.println(new String(bytes));
        System.out.println(new String(bytes2));
        System.out.println(new String(bytes3));
输出结果.png

指定相对应编码格式后,可以正常显示。

System.out.println(new String(bytes3,"utf-16be"));

File类

File只能代表文件(路径),用于表示文件的信息等,不能用于显示文件内容。

常用方法:

        File file = new File("./aimFile");
        if (file.exists()){
            file.delete();//delete file
        }else {
            file.mkdir();//make directory
        }

        File file2 = new File("./","file.txt");
        try {
            file2.createNewFile();//create file
        } catch (IOException e) {
            e.printStackTrace();
        }
        //getFileName
        System.out.println("getFileName (File is directory):" + file.getName()); //aimFile
        System.out.println("getFileName (File is file):" + file2.getName()); //file.txt

RandomAccessFile

与File对象不同,RandomAccessFile可以用于读写文件,可以读写于文件的任意位置。
创建该类型的时候除了file对象,还需要读写方式:r rw

RandomAccessFile randomAccessFile = new RandomAccessFile(new File("F:\\HS"),"rw");

randomAccessFile.seek(0);
byte[] bytes = new byte[(int)randomAccessFile.length()];
randomAccessFile.read(bytes);

因为是随机读写,所以该对象内部含有一个pointer,初始pointer为0;
可以使用seek定位pointer,从而将其内容读入byte[]。

你可能感兴趣的:(java学习笔记#4-File)