Java/File Input Output/ByteBuffer

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

Содержание

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

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Applying Regular Expressions on the Contents of a File

   <source lang="java">

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();
   }
 }

}

</source>
   
  
 
  



Converting Between a ByteBuffer an a Byte Array

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Convert interchangeably between a ByteBuffer and a byte array

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Create a ByteBuffer

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Create a ByteBuffer using a byte array

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Create a character ByteBuffer

   <source lang="java">

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();
 }

}

 </source>
   
  
 
  



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

   <source lang="java">

import java.nio.ByteBuffer; public class Main {

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

}

 </source>
   
  
 
  



Create a double ByteBuffer

   <source lang="java">

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();
 }

}

 </source>
   
  
 
  



Create a float ByteBuffer

   <source lang="java">

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();
 }

}

 </source>
   
  
 
  



Create a long ByteBuffer

   <source lang="java">

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();
 }

}

 </source>
   
  
 
  



Create an integer ByteBuffer

   <source lang="java">

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();
 }

}

 </source>
   
  
 
  



Create a non-direct ByteBuffer with a 10 byte capacity

   <source lang="java">

import java.nio.ByteBuffer; public class Main {

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

}

 </source>
   
  
 
  



Create a short ByteBuffer

   <source lang="java">

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();
 }

}

 </source>
   
  
 
  



Determining If a ByteBuffer Is Direct

   <source lang="java">

//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
 }

}

 </source>
   
  
 
  



Fast Copy File

   <source lang="java">

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();
   }
 }

}

 </source>
   
  
 
  



Get and Set char type data in a ByteBuffer

   <source lang="java">

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();
 }

}

 </source>
   
  
 
  



Get and Set double type data in a ByteBuffer

   <source lang="java">

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();
 }

}

 </source>
   
  
 
  



Get and Set float type data in a ByteBuffer

   <source lang="java">

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();
 }

}

 </source>
   
  
 
  



Get and Set int type data in a ByteBuffer

   <source lang="java">

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();
 }

}

 </source>
   
  
 
  



Get and Set long type data in a ByteBuffer

   <source lang="java">

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();
 }

}

 </source>
   
  
 
  



Get and Set short type data in a ByteBuffer

   <source lang="java">

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();
 }

}

 </source>
   
  
 
  



Get a substring

   <source lang="java">

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
 }

}

 </source>
   
  
 
  



Get default byte ordering

   <source lang="java">

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
 }

}

 </source>
   
  
 
  



Get remaining byte count in a ByteBuffer

   <source lang="java">

import java.nio.ByteBuffer; public class Main {

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

}

 </source>
   
  
 
  



Get the ByteBuffer"s capacity

   <source lang="java">

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
 }

}

 </source>
   
  
 
  



How to get bytes from a ByteBuffer

   <source lang="java">

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
   

}}

 </source>
   
  
 
  



Put a multibyte value

   <source lang="java">

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
 }

}

 </source>
   
  
 
  



Put bytes into a ByteBuffer

   <source lang="java">

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
 }

}

 </source>
   
  
 
  



Putting Bytes into a ByteBuffer

   <source lang="java">

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(); 
 }

}

 </source>
   
  
 
  



Reading from a Channel with a ByteBuffer

   <source lang="java">

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();
     }
   }
 }

}

 </source>
   
  
 
  



Retrieve all bytes in the buffer

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Retrieve bytes between the position and limit

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Set the limit for ByteBuffer

   <source lang="java">

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
 }

}

 </source>
   
  
 
  



Set the position

   <source lang="java">

import java.nio.ByteBuffer; public class Main {

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

}

 </source>
   
  
 
  



Set to little endian

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



This convenience method sets the position to 0

   <source lang="java">

import java.nio.ByteBuffer; public class Main {

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

}

 </source>
   
  
 
  



use FileChannel and ByteBuffer

   <source lang="java">

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(); 
   }
 }

}

 </source>
   
  
 
  



Use NIO to read a text file.

   <source lang="java">
 

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);
   }
 }

}

 </source>
   
  
 
  



Use the absolute get().

   <source lang="java">

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
 }

}

 </source>
   
  
 
  



Use the relative get()

   <source lang="java">

import java.nio.ByteBuffer; public class Main {

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

}

 </source>
   
  
 
  



Using a ByteBuffer to Store Strings

   <source lang="java">

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
 }

}

 </source>
   
  
 
  



View buffers

   <source lang="java">
 

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();
   }
 }

}

 </source>
   
  
 
  



Write with ByteBuffer

   <source lang="java">

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();
 }

}

 </source>
   
  
 
  



Writing and Appending a ByteBuffer to a File

   <source lang="java">

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();
 }

}

 </source>