对文件进行读写:
package dqd.io;
import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import org.omg.CORBA.Request;
/**
* NIO入门
* @author dqd
*/
public class TestIO {
public static void main(String[] args) throws IOException {
RandomAccessFile aFile = new RandomAccessFile("log/sys.out.txt", "rw");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(48);
int size = inChannel.read(buf);
System.out.println(size);
int totalSize = (int) inChannel.size();
String newData = "New String to write to file..." + System.currentTimeMillis();
buf = ByteBuffer.allocate(148);
buf.put(newData.getBytes());
buf.flip();
//将可能存在缓冲区的数据强制的放入磁盘上
inChannel.force(true);
//一个汉字两个字节
inChannel.position(totalSize);
while(buf.hasRemaining()){
inChannel.write(buf);
}
//注意关闭
inChannel.close();
}
}