技术栈

2019-04-30——Java IO RandomAccess

2019-04-30  本文已影响0人  烟雨乱平生

RandomAccessFile类实现了DataOutput和DataInput,所有该类既可以读文件也可以写文件。与普通的输入/输出流不同的是它可以自由访问文件的任意位置。

方法

方法 说明
void seek(long pos) 可以将指针移动到某个位置开始读写;
native void setLength(long newLength) 给写入文件预留空间
    /*多线程读取文件*/
    private void useRandomAccessFile(String filePath) throws FileNotFoundException {
        byte[] data = new byte[1024];
        File file = new File(filePath);
        /*获取文件长度*/
        long length = file.length();
        /*每个线程处理的长度*/
        long total = 1024*1;
        /*计算线程的总数*/
        int number = (int) (length/total)+1;
        /*获取系统内核数量*/
        int count = Runtime.getRuntime().availableProcessors();
        ExecutorService threadPool = new ThreadPoolExecutor(count,count*3,60, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());
        for(int i = 0; i<number; i++){
            int n = i;
            threadPool.execute(()->{
                try {
                    RandomAccessFile raf = new RandomAccessFile(file,"rw");
                    raf.seek(total*n);
                    int totalSize = 0;
                    int size;
                    while ((size=raf.read(data))!=-1&&(totalSize+=size)<=total){
                        String content = new String(data,0,size);
                        System.out.println(content);
                    }
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
        threadPool.shutdown();
    }
上一篇下一篇

猜你喜欢

热点阅读