Advertisement
Guest User

FileReadBuffer

a guest
Jan 20th, 2015
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.29 KB | None | 0 0
  1. package org.andy.example;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.nio.ByteBuffer;
  6. import java.nio.channels.FileChannel;
  7. import java.nio.file.Paths;
  8. import java.nio.file.StandardOpenOption;
  9. import java.util.Arrays;
  10.  
  11. /**
  12.  *
  13.  * @author andy
  14.  */
  15. public class FileReadBuffer {
  16.  
  17.     private static final int CHUNK_SIZE = 1024 * 100;
  18.     private static final String PATH = "/data/VM/Security.vdi";
  19.  
  20.     public static void main(String[] args) throws IOException {
  21.         readFileDirect();
  22.         readFileIndirect();
  23.         readFileUsual();
  24.     }
  25.  
  26.     private static void readFileDirect() throws IOException {
  27.         final ByteBuffer buffer = ByteBuffer.allocateDirect(CHUNK_SIZE);
  28.         long time1 = System.currentTimeMillis();
  29.         readFileBuffer(buffer);
  30.         timeElapsed(time1);
  31.     }
  32.  
  33.     private static void readFileIndirect() throws IOException {
  34.         final ByteBuffer buffer = ByteBuffer.allocate(1024 * 10);
  35.         long time1 = System.currentTimeMillis();
  36.         readFileBuffer(buffer);
  37.         timeElapsed(time1);
  38.     }
  39.  
  40.     private static void readFileBuffer(ByteBuffer buffer) throws IOException {
  41.         String path = PATH;
  42.         FileChannel fc = FileChannel.open(Paths.get(path), StandardOpenOption.READ);
  43.         int read = fc.read(buffer);
  44.         long total = read;
  45.         while (read >= 0) {
  46.             total += read;
  47.             buffer.clear();
  48.             read = fc.read(buffer);
  49.         }
  50.         System.out.println("Total: " + total);
  51.         fc.close();
  52.     }
  53.  
  54.     private static void readFileUsual() throws IOException {
  55.         byte[] data = new byte[CHUNK_SIZE];
  56.         long time1 = System.currentTimeMillis();
  57.         try (FileInputStream fs = new FileInputStream(PATH)) {
  58.             int read = fs.read(data, 0, data.length);
  59.             long total = read;
  60.             while (read >= 0) {
  61.                 total += read;
  62.                 Arrays.fill(data, (byte) 0);
  63.                 read = fs.read(data, 0, data.length);
  64.             }
  65.             System.out.println("Total: " + total);
  66.         }
  67.         timeElapsed(time1);
  68.     }
  69.  
  70.     private static void timeElapsed(long time1) {
  71.         long time2 = System.currentTimeMillis();
  72.         System.out.println("Time:" + (time2 - time1));
  73.     }
  74.  
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement