FileChannel
FileLock ...文件锁操作
lock(),tryLock(),
关于锁定的方式:
共享锁:允许多个线程进行文件的读取操作;
独占锁:只允许一个线程进行文件的读写操作。
字符集:有个Charset类来负责处理编码的问题,
包含了创建编码器(CharsetEncoder)和创建解码器(CharsetDecoder)的操作
Selector,构建一个非阻塞的网络服务。
之前在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(); } } }