java nio的简单用法

import java.nio.*;
import java.util.Scanner;

public class F1 {
	public static void main(String[] args) {
		ByteBuffer bu = ByteBuffer.allocate(20);
		bu.put(new Scanner(System.in).nextLine().trim().getBytes());
		bu.flip();
		System.out.println(bu.get());
		bu.flip();
		//这里要注意输出之后,flip反转之后长度只有一了
		System.out.println("1----" + bu.limit());		
		byte[] byt = new byte[bu.limit()];
		bu.get(byt);// 只获取单个字节
		System.out.println(new String(byt));
		
		
	}
}

 

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class F2 {
	public static void main(String[] args) throws Exception {
		FileInputStream   fin =  new FileInputStream("D:\\zuoye/o.txt");
		FileOutputStream   fout =  new FileOutputStream("D:\\zuoye/q1.txt");
		
		FileChannel  finc = fin.getChannel();//输入流转换成通道
		FileChannel  foutc =fout.getChannel();//输入流转换成通道
		
		ByteBuffer   bf = ByteBuffer.allocate(fin.available());
		finc.read(bf);//对于ByteBuffer来讲,现在是写的模式,写进内存里   
		System.out.println(new String(bf.array()));
		bf.flip();//还原所有的文件指针
		foutc.write(bf);//对于ByteBuffer来讲,现在是读的模式   从内存中读出来 
		bf.clear();
		fin.close();
		fout.close();
		
	}
}

 大文件的复制

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
public class F3 {
	public static void main(String[] args) throws Exception {
	FileChannel big=new RandomAccessFile("D:\\zuoye/o.txt","rw").getChannel();
			//fileChannel不能单独被打开
			//,需要通过使用一个InputStream、
			//OutputStream或RandomAccessFile来获取一个FileChannel实例
	FileChannel cha=new RandomAccessFile("D:\\zuoye/q2.txt","rw").getChannel();
	 //会在内存中映射一个和原文件大小的内存块
	MappedByteBuffer map=big.map(MapMode.READ_WRITE, 0, big.size());
	big.read(map);
	map.flip();
	cha.write(map);
	map.clear();
	big.close();
	cha.close();
	/*这里有个问题,如果q2.txt里有文字,且比o的长度长,o
	 * 里的内容不会写到q2里*/
	
	
	}
}

 

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class F4 {
	public static void main(String[] args) throws Exception {
		FileInputStream in = new FileInputStream("D:\\zuoye/o.txt");
		FileOutputStream out = new FileOutputStream("D:\\zuoye/q3.txt");
		FileChannel inf = in.getChannel();
		FileChannel outf = out.getChannel();
		ByteBuffer by = ByteBuffer.allocate(1024);
		int i;
		while ((i = inf.read(by)) != -1) {
			by.flip();
			outf.write(by);
			by.clear();
		}
		inf.close();
		outf.close();
		in.close();
		out.close();

	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值