Use memory-mapped buffers and scatter/gather to create HTTP replies with mapped files and gathering writes - Java File Path IO

Java examples for File Path IO:MappedByteBuffer

Description

Use memory-mapped buffers and scatter/gather to create HTTP replies with mapped files and gathering writes

Demo Code

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

public class Main {
  private static final String OUTPUT_FILE = "MappedHttp.out";

  private static final String LINE_SEP = "\r\n";
  private static final String HTTP_HDR = "HTTP/1.0 200 OK" + LINE_SEP  + "test" + LINE_SEP;
  private static final String HTTP_404_HDR = "HTTP/1.0 404 Not Found" + LINE_SEP + "test" + LINE_SEP;
  private static final String MSG_404 = "Could not open file: ";

  public static void main(String[] argv) throws Exception {
    String file = "test.dat";
    ByteBuffer header = ByteBuffer.wrap(HTTP_HDR.getBytes("US-ASCII"));
    ByteBuffer dynhdrs = ByteBuffer.allocate(128);
    ByteBuffer[] gather = { header, dynhdrs, null };
    String contentType = "unknown/unknown";
    long contentLength = -1;

    try {//from ww w  . j  a v  a 2  s.  c o  m
      FileInputStream fis = new FileInputStream(file);
      FileChannel fc = fis.getChannel();
      MappedByteBuffer filedata = fc.map(MapMode.READ_ONLY, 0, fc.size());

      gather[2] = filedata;

      contentLength = fc.size();
      contentType = URLConnection.guessContentTypeFromName(file);
      fis.close();
    } catch (IOException e) {
      ByteBuffer buf = ByteBuffer.allocate(128);
      String msg = MSG_404 + e + LINE_SEP;
      buf.put(msg.getBytes("US-ASCII"));
      buf.flip();
      gather[0] = ByteBuffer.wrap(HTTP_404_HDR.getBytes("US-ASCII"));
      gather[2] = buf;
      contentLength = msg.length();
      contentType = "text/plain";
    }

    StringBuffer sb = new StringBuffer();
    sb.append("Content-Length: " + contentLength);
    sb.append(LINE_SEP);
    sb.append("Content-Type: ").append(contentType);
    sb.append(LINE_SEP).append(LINE_SEP);

    dynhdrs.put(sb.toString().getBytes("US-ASCII"));
    dynhdrs.flip();

    FileOutputStream fos = new FileOutputStream(OUTPUT_FILE);
    FileChannel out = fos.getChannel();

    while (out.write(gather) > 0) {
      // Empty body; loop until all buffers are empty
    }

    out.close();
    fos.close();
    System.out.println("output written to " + OUTPUT_FILE);
  }
}

Result


Related Tutorials