集册 Java实例教程 用SeekableByteChannel读取文件

用SeekableByteChannel读取文件

欢马劈雪     最近更新时间:2020-01-02 10:19:05

540
用SeekableByteChannel读取文件

import java.io.*;

import java.nio.*;

import java.nio.file.*;//来自 n o w    j a v a  . c o m

import java.nio.channels.*;


public class FindInt {

    private Path file;


    FindInt(Path file) {

        this.file = file;

    }


    public int seek() throws IOException {

        int num = -1;


        try (SeekableByteChannel fc = Files.newByteChannel(file)) {


            ByteBuffer buf = ByteBuffer.allocate(8);


            //Get the offset into the file.

            fc.read(buf);
            /*
             from NowJava.com - 时  代  Java 
            */

            long offset = buf.getLong(0);


            //Seek to the offset location.

            fc.position(offset);

            buf.rewind();


            //Read the 'secret' value.

            fc.read(buf);

            num = buf.getInt(0);

        } catch (IOException x) {

            System.err.println(x);

        }

        return num;

    }


    public static void main(String[] args) throws IOException {

        Path file = Paths.get("datafile");

        int num = new FindInt(file).seek();

        System.out.println("The value is " + num);

    }

}


展开阅读全文