Java/File Input Output/ByteBuffer — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 06:04, 1 июня 2010

Содержание

A ByteBuffer is a fixed-capacity buffer that holds byte values.

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    
    byte[] bytes = new byte[10];
    ByteBuffer buf = ByteBuffer.wrap(bytes);
  }
}





Applying Regular Expressions on the Contents of a File

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
  public static CharSequence fromFile(String filename) throws IOException {
    FileInputStream fis = new FileInputStream(filename);
    FileChannel fc = fis.getChannel();
    // Create a read-only CharBuffer on the file
    ByteBuffer bbuf = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int) fc.size());
    CharBuffer cbuf = Charset.forName("8859_1").newDecoder().decode(bbuf);
    return cbuf;
  }
  public static void main(String[] argv) throws Exception {
    // Create matcher on file
    Pattern pattern = Pattern.rupile("pattern");
    Matcher matcher = pattern.matcher(fromFile("infile.txt"));
    // Find all matches
    while (matcher.find()) {
      // Get the matching string
      String match = matcher.group();
    }
  }
}





Converting Between a ByteBuffer an a Byte Array

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a ByteBuffer from a byte array
    byte[] bytes = new byte[10];
    ByteBuffer buf = ByteBuffer.wrap(bytes);
  }
}





Convert interchangeably between a ByteBuffer and a byte array

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a ByteBuffer from a byte array
    byte[] bytes = new byte[10];
    ByteBuffer buffer = ByteBuffer.wrap(bytes);
    // Retrieve bytes between the position and limit
    bytes = new byte[buffer.remaining()];
    buffer.get(bytes, 0, bytes.length);
    // Retrieve all bytes in the buffer
    buffer.clear();
    bytes = new byte[buffer.capacity()];
    buffer.get(bytes, 0, bytes.length);
  }
}





Create a ByteBuffer

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a ByteBuffer using a byte array
    byte[] bytes = new byte[10];
    ByteBuffer buffer = ByteBuffer.wrap(bytes);
    // Create a non-direct ByteBuffer with a 10 byte capacity
    // The underlying storage is a byte array.
    buffer = ByteBuffer.allocate(10);
    // Create a memory-mapped ByteBuffer with a 10 byte capacity.
    buffer = ByteBuffer.allocateDirect(10);
  }
}





Create a ByteBuffer using a byte array

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    
    byte[] bytes = new byte[10];
    ByteBuffer buf = ByteBuffer.wrap(bytes);
  }
}





Create a character ByteBuffer

 
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(15);
    CharBuffer cbuf = buf.asCharBuffer();
  }
}





Create a direct (memory-mapped) ByteBuffer with a 10 byte capacity.

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocateDirect(10);
  }
}





Create a double ByteBuffer

 
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(15);
    DoubleBuffer dbuf = buf.asDoubleBuffer();
  }
}





Create a float ByteBuffer

 
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(15);
    FloatBuffer fbuf = buf.asFloatBuffer();
  }
}





Create a long ByteBuffer

 
import java.nio.ByteBuffer;
import java.nio.LongBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(15);
    LongBuffer lbuf = buf.asLongBuffer();
  }
}





Create an integer ByteBuffer

 
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(15);
    IntBuffer ibuf = buf.asIntBuffer();
  }
}





Create a non-direct ByteBuffer with a 10 byte capacity

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(10);
  }
}





Create a short ByteBuffer

 
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(15);
    ShortBuffer sbuf = buf.asShortBuffer();
  }
}





Determining If a ByteBuffer Is Direct

 
//Contents in a non-direct ByteBuffer are stored in the normal memory. 
//Contents in a direct ByteBuffer are stored in some I/O device.
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer bbuf = ByteBuffer.wrap(new byte[10]);
    boolean isDirect = bbuf.isDirect(); // false
    bbuf = ByteBuffer.allocate(10);
    isDirect = bbuf.isDirect(); // false
    bbuf = ByteBuffer.allocateDirect(10);
    isDirect = bbuf.isDirect(); // true
  }
}





Fast Copy File

 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class Main {
  static public void main(String args[]) throws Exception {
    FileInputStream fin = new FileInputStream("infile.txt");
    FileOutputStream fout = new FileOutputStream("outfile.txt");
    FileChannel inc = fin.getChannel();
    FileChannel outc = fout.getChannel();
    ByteBuffer bb = ByteBuffer.allocateDirect(1024);
    while (true) {
      int ret = inc.read(bb);
      if (ret == -1)
        break;
      bb.flip();
      outc.write(bb);
      bb.clear();
    }
  }
}





Get and Set char type data in a ByteBuffer

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(100);
    // Put values of different types
    buf.putChar((char) 123);
    // Reset position for reading
    buf.flip();
    // Retrieve the values
    char c = buf.getChar();
  }
}





Get and Set double type data in a ByteBuffer

 

import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(100);
    // Put values of different types
    buf.putDouble(12.3D);
    // Reset position for reading
    buf.flip();
    // Retrieve the values
    double d = buf.getDouble();
  }
}





Get and Set float type data in a ByteBuffer

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(100);
    // Put values of different types
    buf.putFloat(12.3F);
    // Reset position for reading
    buf.flip();
    // Retrieve the values
    float f = buf.getFloat();
  }
}





Get and Set int type data in a ByteBuffer

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(100);
    // Put values of different types
    buf.putInt(123);
    // Reset position for reading
    buf.flip();
    // Retrieve the values
    int i = buf.getInt();
  }
}





Get and Set long type data in a ByteBuffer

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(100);
    // Put values of different types
    buf.putLong(123L);
    // Reset position for reading
    buf.flip();
    // Retrieve the values
    long l = buf.getLong();
  }
}





Get and Set short type data in a ByteBuffer

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(100);
    buf.putShort((short) 123);
    // Reset position for reading
    buf.flip();
    // Retrieve the values
    short s = buf.getShort();
  }
}





Get a substring

 
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(100);
    CharBuffer cbuf = buf.asCharBuffer();
    cbuf.put("a string");
    int start = 2; // start is relative to cbuf"s current position
    int end = 5;
    CharSequence sub = cbuf.subSequence(start, end); // str
  }
}





Get default byte ordering

 
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(10);
    
    ByteOrder order = buf.order(); // ByteOrder.BIG_ENDIAN
  }
}





Get remaining byte count in a ByteBuffer

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocateDirect(10);
    int rem = buf.remaining();
  }
}





Get the ByteBuffer"s capacity

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocateDirect(10);
    int capacity = buf.capacity(); // 10
  }
}





How to get bytes from a ByteBuffer

 
public class Main{
public static void main(String[] argv) throws Exception{
    // Create an empty ByteBuffer with a 10 byte capacity
    ByteBuffer bbuf = ByteBuffer.allocate(10);
    
    // Retrieve the capacity of the ByteBuffer
    int capacity = bbuf.capacity(); // 10
    
    // The position is not affected by the absolute get() method.
    byte b = bbuf.get(5); // position=0
    
    // Set the position
    bbuf.position(5);
    
    // Use the relative get()
    b = bbuf.get();
    
    // Get the new position
    int pos = bbuf.position(); 
    
    // Get remaining byte count
    int rem = bbuf.remaining();
    
    // Set the limit
    bbuf.limit(7); // remaining=1
    
    // This convenience method sets the position to 0
    bbuf.rewind(); // remaining=7
    
}}





Put a multibyte value

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(10);
    buf.putShort(0, (short) 123);
    buf.get(0); // 0
    buf.get(1); // 123
  }
}





Put bytes into a ByteBuffer

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create an empty ByteBuffer with a 10 byte capacity
    ByteBuffer bbuf = ByteBuffer.allocate(10);
    // Retrieve the capacity of the ByteBuffer
    int capacity = bbuf.capacity(); // 10
    // The position is not affected by the absolute get() method.
    byte b = bbuf.get(5); // position=0
    // Set the position
    bbuf.position(5);
    // Use the relative get()
    b = bbuf.get();
    // Get the new position
    int pos = bbuf.position(); // 6
    // Get remaining byte count
    int rem = bbuf.remaining(); // 4
    // Set the limit
    bbuf.limit(7); // remaining=1
    // This convenience method sets the position to 0
    bbuf.rewind(); // remaining=7
  }
}





Putting Bytes into a ByteBuffer

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer bbuf = ByteBuffer.allocate(10);
    int capacity = bbuf.capacity(); // 10
    System.out.println(capacity);
    bbuf.put((byte) 0xFF); 
    bbuf.position(5);
    bbuf.put((byte) 0xFF);
    int pos = bbuf.position(); 
    int rem = bbuf.remaining();
    bbuf.limit(7); 
    bbuf.rewind(); 
  }
}





Reading from a Channel with a ByteBuffer

 
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
public class Main {
  public static void main(String[] argv) throws Exception {
    ReadableByteChannel channel = new FileInputStream("infile").getChannel();
    ByteBuffer buf = ByteBuffer.allocateDirect(10);
    int numRead = 0;
    while (numRead >= 0) {
      buf.rewind();
      numRead = channel.read(buf);
      buf.rewind();
      // Read bytes from ByteBuffer; see also
      for (int i = 0; i < numRead; i++) {
        byte b = buf.get();
      }
    }
  }
}





Retrieve all bytes in the buffer

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    byte[] bytes = new byte[10];
    ByteBuffer buf = ByteBuffer.wrap(bytes);
    buf.clear();
    bytes = new byte[buf.capacity()];
    buf.get(bytes, 0, bytes.length);
  }
}





Retrieve bytes between the position and limit

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    byte[] bytes = new byte[10];
    ByteBuffer buf = ByteBuffer.wrap(bytes);
    bytes = new byte[buf.remaining()];
    buf.get(bytes, 0, bytes.length);
  }
}





Set the limit for ByteBuffer

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocateDirect(10);
    buf.limit(7); // remaining=1
  }
}





Set the position

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocateDirect(10);
    buf.position(5);
  }
}





Set to little endian

 
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(10);
    buf.order(ByteOrder.LITTLE_ENDIAN);
  }
}





This convenience method sets the position to 0

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocateDirect(10);
    buf.rewind(); // remaining=7
  }
}





use FileChannel and ByteBuffer

 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class Main {
  static public void main(String args[]) throws Exception {
    FileInputStream fin = new FileInputStream("infile.txt");
    FileOutputStream fout = new FileOutputStream("outfile.txt");
    FileChannel inc = fin.getChannel();
    FileChannel outc = fout.getChannel();
    ByteBuffer bb = ByteBuffer.allocate(1024);
    while (true) {
      int ret = inc.read(bb);
      if (ret == -1) 
        break;
      bb.flip();
      outc.write(bb);
      bb.clear(); 
    }
  }
}





Use NIO to read a text file.

  
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ExplicitChannelRead {
  public static void main(String args[]) {
    FileInputStream fIn;
    FileChannel fChan;
    long fSize;
    ByteBuffer mBuf;
    try {
      fIn = new FileInputStream("test.txt");
      fChan = fIn.getChannel();
      fSize = fChan.size();
      mBuf = ByteBuffer.allocate((int) fSize);
      fChan.read(mBuf);
      mBuf.rewind();
      for (int i = 0; i < fSize; i++)
        System.out.print((char) mBuf.get());
      fChan.close(); 
      fIn.close(); 
    } catch (IOException exc) {
      System.out.println(exc);
      System.exit(1);
    }
  }
}





Use the absolute get().

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocateDirect(10);
    byte b = buf.get(5); // position=0
  }
}





Use the relative get()

 
import java.nio.ByteBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocateDirect(10);
    byte b = buf.get();
  }
}





Using a ByteBuffer to Store Strings

 
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(100);
    CharBuffer cbuf = buf.asCharBuffer();
    cbuf.put("a string");
    cbuf.flip();
    String s = cbuf.toString(); // a string
  }
}





View buffers

  
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.FloatBuffer;
public class Buffers {
  public static void main(String[] args) {
    try {
      float[] floats = { 6.61E-39F, 9.918385E-39F};
      ByteBuffer bb = ByteBuffer.allocate(floats.length * 4);
      FloatBuffer fb = bb.asFloatBuffer();
      fb.put(floats);
      CharBuffer cb = bb.asCharBuffer();
      System.out.println(cb.toString());
    } catch (Exception e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
    }
  }
}





Write with ByteBuffer

 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class Main {
  public static void main(String[] args) throws Exception {
    String fromFileName = "from.txt";
    String toFileName = "to.txt";
    FileChannel in = new FileInputStream(fromFileName).getChannel();
    FileChannel out = new FileOutputStream(toFileName).getChannel();
    ByteBuffer buff = ByteBuffer.allocateDirect(32 * 1024);
    while (in.read(buff) > 0) {
      buff.flip();
      out.write(buff);
      buff.clear();
    }
    in.close();
    out.close();
  }
}





Writing and Appending a ByteBuffer to a File

 
import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer bbuf = ByteBuffer.allocate(100);
    File file = new File("filename");
    boolean append = false;
    FileChannel wChannel = new FileOutputStream(file, append).getChannel();
    wChannel.write(bbuf);
    wChannel.close();
  }
}