java Memorymapfile demo

String lineseperator = java.security.AccessController .doPrivileged(new sun.security.action.GetPropertyAction( "line.separator"));

Access restriction: The constructor 'GetPropertyAction(String)' is not API

Access restriction on class due to restriction on required library rt.jar?

  1. Go to the Build Path settings in the project properties.
  2. Remove the JRE System Library
  3. Add it back; Select "Add Library" and select the JRE System Library. The default worked for me.
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

public class memorymapfiledemo {
    final static String filepath = "/home/hadoop/test/java.txt";

    public static void main(String[] args) throws IOException {
        writefile(filepath);
        readfile(filepath);
    }

    static void writefile(String _filepath) throws IOException {
        File _file = new File(_filepath);
        RandomAccessFile raf = new RandomAccessFile(_file, "rw");
        FileChannel fc = raf.getChannel();
        int buffersize = 1024 * 8;
        CharBuffer cb = fc.map(MapMode.READ_WRITE, 0, buffersize)
                .asCharBuffer();
        String lineseperator = java.security.AccessController
                .doPrivileged(new sun.security.action.GetPropertyAction(
                        "line.separator"));
        String content = "";
        long offset = 0;
        for (int i = 1; i <= 1000; i++) {
            content = "Line" + i + " hello java" + lineseperator;
            if ((cb.limit() - cb.position()) < content.length()) {
                offset += cb.position();
                cb = fc.map(MapMode.READ_WRITE, offset, buffersize)
                        .asCharBuffer();
            }
            cb.put(content);
        }
        fc.close();
        raf.close();
    }

    static void readfile(String _filepath) throws IOException {
        File _file = new File(_filepath);
        RandomAccessFile raf = new RandomAccessFile(_file, "rw");
        FileChannel fc = raf.getChannel();
        long totalsize = fc.size();
        int buffersize = 1024 * 8;
        long offset = 0;
        CharBuffer cb = fc.map(MapMode.READ_ONLY, 0, buffersize).asCharBuffer();
        while (offset < totalsize) {
            while (cb.hasRemaining()) {
                System.out.print(cb.get());
            }
            offset += cb.position();
            cb = fc.map(MapMode.READ_ONLY, offset, buffersize).asCharBuffer();
        }
        fc.close();
        raf.close();
    }
}

posted on 2015-02-28 11:14  tneduts  阅读(682)  评论(0编辑  收藏  举报

导航