`
胡小米
  • 浏览: 75806 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

FileChannel 类(转)

    博客分类:
  • Java
阅读更多
java.nio.channels.FileChannel 用于读取、写入、映射和操作文件的通道,类的定义:public abstract class FileChannel 。
文件通道在其文件中有一个当前 position,可对其进行查询和修改。该文件本身包含一个可读写的长度可变的字节序列,并且可以查询该文件的当前#size大小。写入的字节超出文件的当前大小时,则增加文件的大小;截取 该文件时,则减小文件的大小。文件可能还有某个相关联的元数据,如访问权限、内容类型和最后的修改时间;此类未定义访问元数据的方法。
下面举几个例子:
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class FileChannelTest1 {
public static void main(String[] args) throws Exception {
File file = new File(”d:\\note.txt”); // 创建新的文件对象
FileInputStream in = new FileInputStream(file); // 创建新的文件输入字节流
FileOutputStream out = new FileOutputStream(”d:\\1.txt”); // 创建新的文件输出字节流
FileChannel fc = in.getChannel(); // 创建一个新的文件输入通道
FileChannel fout = out.getChannel(); // 创建新的文件输出通道
ByteBuffer buf = ByteBuffer.allocate(1024); // 创建新的字节缓冲区
int c = 0;
while((c = fc.read(buf))!=-1){ // 将字节序列从此通道读入给定的缓冲区
buf.flip();
fout.write(buf); // 将字节序列从给定的缓冲区写入此通道。
buf.clear();
}
fout.close();
fc.close();
in.close();
out.close();
}
}
=========================================================
//文件锁定
import java.io.File;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class FileLockTest1 {
public static void main(String[] args) throws Exception {
File file = new File(”d://note.txt”);
FileOutputStream out = new FileOutputStream(file,true);
FileChannel fout = out.getChannel();
FileLock lock = fout.lock();//独占锁
if(lock!=null){
System.out.println(”文件被锁定了”);
Thread.sleep(20000);
lock.release();
System.out.println(”文件被释放了”);
}
fout.close();
out.close();
}
}
=========================================================
// MappedByteBuffer类 直接字节缓冲区,其内容是文件的内存映射区域。
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
public class MappedByteBufferTest {
public static void main(String[] args) throws Exception{
File file = new File(”d:\\note.txt”);
FileInputStream in = new FileInputStream(file);
FileChannel fc = in.getChannel();
MappedByteBuffer mbb = fc.map(MapMode.READ_ONLY, 0, file.length());
System.out.println(mbb.position()); // 输出结果: 0
//ByteBuffer buf = ByteBuffer.allocate((int)file.length());
byte[] data = new byte[(int)file.length()];
int index = 0;
while(mbb.hasRemaining()){
data[index] = mbb.get();
index++;
}
System.out.println(new String(data));

//用内存映射的方式读是最快的,但是很危险,建议只读
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics