RandomAccessFile文本操作

对文本的操作需要将字符串转换为字节(10101010的格式),然后进行读写操作

写入操作

public static void main(String[] args) throws IOException {
    
    
        RandomAccessFile raf = new RandomAccessFile("raf.txt","rw");
        String str = "左边-跟我一起画个龙";

        /*
        * String对象的方法
        * byte[] getBytes();
        * 功能是将字符串中的字符转换成字节
        * 按照系统默认的字符集
        *
        * byte[] getBytes(String csn)
        * 功能是将字符串中的字符转成字节
        * 按照指定的字符集
        * */
        byte[] data = str.getBytes();
        raf.write(data);
        System.out.println("over");
        raf.close();
    }

读取操作

public static void main(String[] args) throws IOException {
    
    
        RandomAccessFile raf = new RandomAccessFile("raf.txt","r");

//        System.out.println(raf.length());

        byte[] data = new byte[(int)raf.length()];
        //读取文件中的所有数据到data数值
        raf.read(data);

        /*
        * String类中有一个构造方法
        * String(byte[] data,String scn)
        * data是字节数组,会按照scn指定的字符集解析字符,并创建对象
        * */

        String str = new String(data,"utf-8"); //字符集也可以不写,如果乱码需要更改字符集
        System.out.println(str);

        raf.close();
    }

利用读写操作完成简易记事本

public class NoteDemo {
    
    
    public static void main(String[] args) throws IOException {
    
    
        Scanner src = new Scanner(System.in);
        //一次读取一整行数据
        System.out.println("请输入文件名称");
        String fileName = src.nextLine();
        RandomAccessFile raf = new RandomAccessFile(fileName,"rw");
        while (true){
    
    
            System.out.println("请输入记事本");
            String msg = src.nextLine();
            if (msg.equals("exit")){
    
    
                //输入exit退出循环
                break;
            }
            byte[] data = msg.getBytes();
            raf.write(data);
        }
        raf.close();
    }
}

Guess you like

Origin blog.csdn.net/sinat_33940108/article/details/120697729