Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package org.andy.example;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.nio.ByteBuffer;
- import java.nio.channels.FileChannel;
- import java.nio.file.Paths;
- import java.nio.file.StandardOpenOption;
- import java.util.Arrays;
- /**
- *
- * @author andy
- */
- public class FileReadBuffer {
- private static final int CHUNK_SIZE = 1024 * 100;
- private static final String PATH = "/data/VM/Security.vdi";
- public static void main(String[] args) throws IOException {
- readFileDirect();
- readFileIndirect();
- readFileUsual();
- }
- private static void readFileDirect() throws IOException {
- final ByteBuffer buffer = ByteBuffer.allocateDirect(CHUNK_SIZE);
- long time1 = System.currentTimeMillis();
- readFileBuffer(buffer);
- timeElapsed(time1);
- }
- private static void readFileIndirect() throws IOException {
- final ByteBuffer buffer = ByteBuffer.allocate(1024 * 10);
- long time1 = System.currentTimeMillis();
- readFileBuffer(buffer);
- timeElapsed(time1);
- }
- private static void readFileBuffer(ByteBuffer buffer) throws IOException {
- String path = PATH;
- FileChannel fc = FileChannel.open(Paths.get(path), StandardOpenOption.READ);
- int read = fc.read(buffer);
- long total = read;
- while (read >= 0) {
- total += read;
- buffer.clear();
- read = fc.read(buffer);
- }
- System.out.println("Total: " + total);
- fc.close();
- }
- private static void readFileUsual() throws IOException {
- byte[] data = new byte[CHUNK_SIZE];
- long time1 = System.currentTimeMillis();
- try (FileInputStream fs = new FileInputStream(PATH)) {
- int read = fs.read(data, 0, data.length);
- long total = read;
- while (read >= 0) {
- total += read;
- Arrays.fill(data, (byte) 0);
- read = fs.read(data, 0, data.length);
- }
- System.out.println("Total: " + total);
- }
- timeElapsed(time1);
- }
- private static void timeElapsed(long time1) {
- long time2 = System.currentTimeMillis();
- System.out.println("Time:" + (time2 - time1));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement