Java新IO

 

FileChanneljava

FileLock ...文件鎖操做 數組

lock(),tryLock(),服務器

關於鎖定的方式:網絡

共享鎖:容許多個線程進行文件的讀取操做;app

獨佔鎖:只容許一個線程進行文件的讀寫操做。socket


字符集:有個Charset類來負責處理編碼的問題,編碼

包含了建立編碼器(CharsetEncoder)和建立解碼器(CharsetDecoder)的操做spa


Selector,構建一個非阻塞的網絡服務。.net

以前在Socket程序的時候,服務器必須始終等着客戶端的鏈接,形成浪費資源,因此引入了非阻塞的IO操做。線程

 把內容寫到文件中去

 

package Demo.javatest;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NewIoChanel_01 {
	/**
	 * 把內容寫到文件中去
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception{
		String info[] = {"wangs","hehe","wangshao","北京"};
		File file = new File("d:"+File.separator+"myfile.txt");
		
		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());  //字符串變爲字節數組放入緩衝區
		}
		buf.flip();
		fout.write(buf);//輸出緩衝區的內容
		fout.close();
		output.close();
		
	}
}
 

讀取文件

package Demo.javatest;
import java.io.File;
import java.io.FileInputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class NewIoChanel_02 {
	/**
	 * 讀取文件
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception{
		File file = new File("d:"+File.separator+"myfile.txt");
		FileInputStream input = null;
		FileChannel fin = null;
		input = new FileInputStream(file);
		fin = input.getChannel();
		MappedByteBuffer mbb = null;
		mbb = fin.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
		byte data [] = new byte[(int) file.length()];
		int foot =0;
		while(mbb.hasRemaining()){
			data[foot++] = mbb.get();
		}
		System.out.println(new String(data));
		fin.close();
		input.close();
	}
}
 

讀取文件,寫到文件中去

package Demo.javatest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NewIoChanel_03 {
	/**
	 * 讀取文件,寫到文件中去
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception{
		File file = new File("d:"+File.separator+"myfile.txt");
		File file2 = new File("d:"+File.separator+"myfile2.txt");
		FileInputStream input= null;
		FileOutputStream output= null;
		input = new FileInputStream(file);
		output = new FileOutputStream(file2);
		FileChannel fout = null;
		FileChannel fin = null;
		fin = input.getChannel();
		fout = output.getChannel();
		ByteBuffer buf = ByteBuffer.allocate(1024);
		int temp = 0;
		while((temp = fin.read(buf))!= -1){      //以1024爲單位,邊讀邊寫
			buf.flip();
			fout.write(buf);
			buf.clear();       //不清空內容進不來,全部變量位置恢復到原點
		}
		fin.close();
		fout.close();
		input.close();
		output.close();
		
	}
}
 

 

 

 

 

 

/**

* 對一個文件進行鎖定 

* @param args FileOutputStream具備可寫操做,FileInputStream找不到寫操做,沒法鎖定

*/

 

package Demo.javatest;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class FileLockDemo {
	/**
	 * 對一個文件進行鎖定 
	 * @param args FileOutputStream具備可寫操做,FileInputStream找不到寫操做,沒法鎖定
	 */
	public static void main(String[] args) throws Exception {
		File file = new File("d:"+File.separator+"myfile.txt");
		FileOutputStream output= null;
		output = new FileOutputStream(file,true);       //這裏須要加true
		FileChannel fout =null;
		fout = output.getChannel();
		FileLock lock = fout.tryLock();
		if(lock!= null){
			System.out.println(file.getName()+"文件被鎖定30秒");
			Thread.sleep(30000);
			lock.release(); //釋放鎖定
			System.out.println(file.getName()+"文件被解鎖");
		}
		fout.close();
		output.close();
	}
}
 

進行編碼,解碼操做。

package Demo.javatest;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
public class CharSetEnDeDemo {
	/**進行編碼,解碼操做。
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		Charset latin1 = Charset.forName("ISO8859-1");
		CharsetEncoder encoder = latin1.newEncoder(); //獲得編碼器
		CharsetDecoder decoder = latin1.newDecoder();//獲得解碼器
		CharBuffer cb = CharBuffer.wrap("hello,charset");   //準備編譯內容
		ByteBuffer bb = encoder.encode(cb);   //進行編碼
		System.out.println(decoder.decode(bb));
	
		
	}
}
 

獲得全部Charset編碼

package Demo.javatest;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
public class GetAllCharSetDemo {
	/**獲得全部Charset編碼
	 * @param args
	 */
	public static void main(String[] args) {
		SortedMap<String, Charset>  all =null;
		all= Charset.availableCharsets();
		Iterator<Map.Entry<String, Charset>> iter= null;
		iter = all.entrySet().iterator();
		while(iter.hasNext()){
			Map.Entry<String, Charset> me=  iter.next();
			System.out.println(me.getKey()+"---->"+me.getValue());
		}
	}
}
 

一個非阻塞的服務器端

package Demo.javatest;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
public class SelectorDemo {
	/**一個非阻塞的服務器端
	 * @param args
	 * @throws Exception 
	 */
	
	public static void main(String[] args) throws Exception {
		int ports[]= {8888,8880,8881,8882};
		Selector selector = Selector.open();
		for(int i=0;i< ports.length;i++){
			ServerSocketChannel initSer = null;
			initSer = ServerSocketChannel.open(); //打開服務器套接字通道
			initSer.configureBlocking(false);   //設置爲非阻塞
			ServerSocket initSock = initSer.socket(); //檢索相關的套接字
			InetSocketAddress address = null;
			address = new InetSocketAddress(ports[i]);  //實例化綁定監聽地址
			initSock.bind(address);
			initSer.register(selector, SelectionKey.OP_ACCEPT); //至關於accept(),註冊選擇器
			System.out.println("服務器運行在"+ports[i]+"端口.");
		}
		
		int addKey = 0;
		while((addKey=selector.select())>0){
			Set<SelectionKey> selectKeys = selector.selectedKeys();
			Iterator<SelectionKey> iter = selectKeys.iterator();
			while(iter.hasNext()){
				SelectionKey key = iter.next();
				if(key.isAcceptable()){
					ServerSocketChannel server = (ServerSocketChannel) key.channel();
					SocketChannel client = server.accept();
					client.configureBlocking(false); //配置爲非阻塞
					ByteBuffer outbuf = ByteBuffer.allocateDirect(1024);
					outbuf.put(("當前的時候:"+new Date()).getBytes());
					outbuf.flip();
					client.write(outbuf);
					client.close();
				}
			}
			selectKeys.clear();
		}
	}
}
 
相關文章
相關標籤/搜索