今天分享SeekabnlerByteChannel API,,通常搭配Files中的ByteChannel,主要功能是可以用position方法指定開始讀取的位置,再指定要讀多少byte,簡單範例如下
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mysee;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
*
* @author joombuopre
*/
public class Mysee {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
Path dw=Paths.get("L:\\Tian.txt");
//01818G773s7Gmmm3mss967s3848s423GSM253smms18gS97159645220s636m75S0s6S85702670mmSggmm78s2482277s8s98M
int bufferSize =8;
try(SeekableByteChannel sb= Files.newByteChannel(dw)){
ByteBuffer buffer= ByteBuffer.allocate(bufferSize);
sb.position(4); // set pointer to 4
sb.read(buffer); // begin read after 4
for(int i=0;i<8;i++){
System.out.print((char)buffer.get(i)); //8G773s7G
}
System.out.println();
buffer.clear();
sb.position(0); //point set back to 0
sb.read(buffer); //read start at 0
for(int i=0;i<4;i++){
System.out.print((char)buffer.get(i)); // 0181
}
System.out.println();
}
}
}