使用RandomAccessFile进行文件的读写

来源:互联网 发布:淘宝c店是什么意思 编辑:程序博客网 时间:2024/04/29 17:11
        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();            }        }
0 0
原创粉丝点击