zoukankan      html  css  js  c++  java
  • RandomAccessFile类的使用(随机读取java中的文件)

    package coreJava;
    
    import java.io.File;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.util.Arrays;
    
    public class RandomAccessFileWriteandRead {
    
        public static void main(String[] args)throws IOException {
            // TODO Auto-generated method stub
    
            File demo = new File("demo");
            if(!demo.exists())
                demo.mkdir();
            File file = new File(demo,"raf.dat");
            if(!file.exists())
                file.createNewFile();
            RandomAccessFile raf = new RandomAccessFile(file,"rw");
            //获取指针的位置:
            System.out.println(raf.getFilePointer());
            
            raf.write('A');//只写了一个字节
            System.out.println(raf.getFilePointer());
            raf.write('B');
            
            int i = 0x7fffffff;
            
            //用write方法一次只能写一个字节。如果要把i写进去的就得写四次
            raf.write(i>>>24);//高8位
            raf.write(i>>>16);
            raf.write(i>>>8);
            raf.write(i);
            System.out.println(raf.getFilePointer());
            //可以直接写一个int
            raf.writeInt(i);
            String s = "中";
            byte[] gbk = s.getBytes("gbk");
            raf.write(gbk);
            System.out.println(raf.length());
        
            //读文件必须把指针移动到头部
            raf.seek(0);
            
            //一次性读取
            byte[] buf = new byte[(int)raf.length()];
            raf.read(buf);
            System.out.println(Arrays.toString(buf));
            for(byte b:buf){
                System.out.print(Integer.toHexString(b & 0xff)+"  ");
            }
            String s1 = new String(buf);
            System.out.println(s1);
            
            //关闭文件
            raf.close();
        
        }
    
    }
  • 相关阅读:
    离线计算框架 MapReduce
    Hadoop概述
    Linux之rpm/yum
    Linux之磁盘分区
    利用CMD合并多个VOB文件
    android中的simple_list_item
    jquery中的跨域-jsonp格式
    安卓代码中设置ImageView属性
    Android中常用的Adapter的种类和用法
    C#导入excel文件到oracle的方法
  • 原文地址:https://www.cnblogs.com/blogofwyl/p/4724716.html
Copyright © 2011-2022 走看看