使用RandomAccessFile进行文件的读写


        RandomAccessFile raf = new RandomAccessFile("test.txt","r");

        byte[] buf = new byte[40];
        int len = raf.read(buf);
        System.out.println("读取的字节>>>> "+len);
        System.out.println(Arrays.toString(buf));

        String str = new String(buf);
        System.out.println(str);

        str = new String(buf,"UTF-8");
        System.out.println(str);
        System.out.println(str.length());

        str = new String(buf,0,len,"UTF-8");
        System.out.println(str);
        raf.close();

2 .写


        RandomAccessFile raf = null;
        try {

            raf = new RandomAccessFile("test.txt","rw") ;  // 读写文件是按照字节为单位进行的

            System.out.println(Integer.toBinaryString((int)'a'));

            raf.write(97);
            raf.write(3);
            raf.writeBytes("a");
            raf.writeChars(" I ma");

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(raf != null){
                raf.close();
            }
        }


你可能感兴趣的:(RandomAcce)