java nio实例一

java nio的实例

 

public class NewIOChannel {
	
	private String file = "";
	private String file2 = "";
	
	@Before
	public void init(){
		file = NewIOChannel.class.getResource("").getPath()+"\\myfile.txt";
		file2 = NewIOChannel.class.getResource("").getPath()+"\\myfile2.txt";
		System.out.println(file);
	}
	
	/**
	 * outputStream channel写文件
	 * @throws IOException
	 */
	@Test
	public void FileTest() throws IOException{
		String info[] = {"wang","fwefwe","北京"};
		File file = new File(this.file);
		
		FileOutputStream output = null;
		output = new FileOutputStream(file);
		FileChannel fout = null;
		fout = output.getChannel();
		ByteBuffer buf = ByteBuffer.allocate(1024);
		for (int i = 0; i < info.length; i++) {
			buf.put(info[i].getBytes("UTF-8"));
		}
		buf.flip();
		fout.write(buf);
		fout.close();
		output.close();
	}
	
	@Test
	public void writeFile()throws IOException{
		File file = new File(this.file);
		FileInputStream input = new FileInputStream(file);
		FileChannel fileChannel = input.getChannel();
		byte data[] = new byte[(int)file.length()];
//		MappedByteBuffer mbb = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
//		int foot = 0;
//		while(mbb.hasRemaining())
//			data[foot++] = mbb.get();
		ByteBuffer bufs = ByteBuffer.wrap(data);
		fileChannel.read(bufs);
		System.out.println(new String(data));
		fileChannel.close();
	}
	
	@Test
	public void writereadFile() throws IOException{
		File file = new File(this.file);
		File file2 = new File(this.file2);
		FileInputStream input = new FileInputStream(file);
		FileOutputStream output = new FileOutputStream(file2);
		
		FileChannel fout = output.getChannel();
		FileChannel fin = input.getChannel();
		ByteBuffer buf = ByteBuffer.allocate(1024);
		int temp =0;
		while ((temp = fin.read(buf)) != -1) {
			buf.flip();
			fout.write(buf);
			buf.clear();
		}
		fin.close();
		fout.close();
	}
	
	@Test
	public void FileLockDemo() throws IOException, InterruptedException{
		File file = new File(this.file);
		FileOutputStream output = new FileOutputStream(file,true);
		FileChannel fout = output.getChannel();
		FileLock lock = fout.tryLock();
		if(lock != null){
			System.out.println(file.getName()+"文件被锁定5秒");
			Thread.sleep(5000);
			lock.release();
			System.out.println(file.getName()+"文件被解锁");
		}
		fout.close();
		output.close();
	}
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值