zoukankan      html  css  js  c++  java
  • JAVA IO

    传统IO流体系

    保存用户输入到文件

    package io;

    import java.io.*;

    public class MyFileOutput {

     

        public static void main(String[] args) {

            FileInputStream fin;

            FileOutputStream fout;

            int ch;

            try {

                fin=new FileInputStream(FileDescriptor.in);

                fout=new FileOutputStream("output.txt");

                System.out.println("请输入一行字符:");

                while((ch=fin.read())!=' ')

                    fout.write(ch);

                fin.close();

                fout.close();

                System.out.println("文件写入成功!");

            } catch (FileNotFoundException e) {

                System.out.println("不能创建文件!");

            }catch(IOException e){

                System.out.println("输出流有误!");

            }

     

        }

     

    }

    显示文本文件的内容

    package io;

    import java.io.*;

    public class TypeFile {

     

        public static void main(String[] args) {

            FileInputStream fin;

            FileOutputStream fout;

            int ch;

            if(args.length<1){

                System.out.println("请指定文件名!");

                return;

            }

            try {

                fin=new FileInputStream(args[0]);

                fout=new FileOutputStream(FileDescriptor.out);

                while((ch=fin.read())!=-1)

                    fout.write(ch);

                fin.close();

                fout.close();

            } catch (FileNotFoundException e) {

                System.out.println("文件没有找到!");

            } catch (IOException e) {

                System.out.println("输入流有误!");

            }

            

        }

     

    }

    RandomAccessFile类进行文件加密

    文件加密/解密示例。

    package io;

    import java.io.*;

    public class encrypt {

        private File file; //存储文件对象信息

        byte[] buf;  //缓冲区,存储文件中的所有数据    RandomAccessFile fp;

        //用参数filename指定的文件构造一个filed对象存储

        //同时为缓冲区buf分配与文件长度相等的存储空间

        public encrypt(String filename){

            file=new File(filename);

            buf=new byte[(int)file.length()];

        }

        

        public encrypt(File destfile){

            file = destfile;

            buf = new byte[(int)file.length()];

        }

        

        //按照读写的方式打开文件

        public void openFile()throws FileNotFoundException{

            fp=new RandomAccessFile(file,"rw");

        }

        

        //关闭文件

        public void closeFile()throws IOException{

            fp.close();

        }

        

        //对文件进行加密/解密

        public void coding()throws IOException{

            //将文件内容读到缓冲区中        fp.read(buf);

            //将缓冲区中的内容取反

            for(int i=0;i<buf.length;i++)

                buf[i]=(byte)(~buf[i]);

            //将文件指针定位到文件头部

            fp.seek(0);

            //将缓冲区中的内容写入到文件中        fp.write(buf);

        }

        

        public static void main(String[] args) {

            encrypt oa;

            if(args.length<1){

                System.out.println("你需要指定加密文件的名字!");

                return;

            }

            try {

                oa = new encrypt(args[0]);

                oa.openFile();

                oa.coding();

                oa.closeFile();

                System.out.println("文件加密成功!");

            } catch (FileNotFoundException e) {

                System.out.println("没有找到文件:"+args[0]);

            }catch (IOException e){

                System.out.println("文件读写错误:"+args[0]);

            }

            

        }

     

    }

    Scanner类

    package io;

    import java.util.*;

    public class useScanner {

     

        public static void main(String[] args) {

            Scanner in=new Scanner(System.in);

            System.out.println("请输入你的姓名:");

            String name=in.nextLine();

            System.out.println("请输入你的年龄:");

            int age=in.nextInt();

            System.out.println("请输入你的身高(单位:米):");

            double height=in.nextDouble();

            System.out.println("姓名:"+name+"年龄:"+age+"身高:"+height);

        }

     

    }

    从键盘输入

    package io;

    import java.io.*;

    public class ReadAndWrite {

     

        public static void main(String[] args) {

            InputStreamReader isr=new InputStreamReader(System.in);

            OutputStreamWriter osr=new OutputStreamWriter(System.out);

            int ch;

            try {

                System.out.print("请输入一行字符:");

                while((ch=isr.read())!=' ')

                    osr.write(ch);

                isr.close();

                osr.close();

            } catch (IOException e) {

                System.out.println("输入流有误!");

            }

            

        }

     

    }

    Java NIO提供了与标准IO不同的IO工作方式: 

    • Channels and Buffers(通道和缓冲区):标准的IO基于字节流和字符流进行操作的,而NIO是基于通道(Channel)和缓冲区(Buffer)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。
    • Asynchronous IO(异步IO):Java NIO可以让你异步的使用IO,例如:当线程从通道读取数据到缓冲区时,线程还是可以进行其他事情。当数据被写入到缓冲区时,线程可以继续处理它。从缓冲区写入通道也类似。
    • Selectors(选择器):Java NIO引入了选择器的概念,选择器用于监听多个通道的事件(比如:连接打开,数据到达)。因此,单个的线程可以监听多个数据通道。

    Java NIO 概述

    Java NIO 由以下几个核心部分组成: 

    • Channels
    • Buffers
    • Selectors

    虽然Java NIO 中除此之外还有很多类和组件,但在我看来,Channel,Buffer 和 Selector 构成了核心的API。其它组件,如Pipe和FileLock,只不过是与三个核心组件共同使用的工具类。因此,在概述中我将集中在这三个组件上。其它组件会在单独的章节中讲到。 

    Channel 和 Buffer 

    基本上,所有的 IO 在NIO 中都从一个Channel 开始。Channel 有点象流。 数据可以从Channel读到Buffer中,也可以从Buffer 写到Channel中。

    Channel和Buffer有好几种类型。下面是JAVA NIO中的一些主要Channel的实现: 

    • FileChannel
    • DatagramChannel
    • SocketChannel
    • ServerSocketChannel

    以下是Java NIO里关键的Buffer实现: 

    • ByteBuffer
    • CharBuffer
    • DoubleBuffer
    • FloatBuffer
    • IntBuffer
    • LongBuffer
    • ShortBuffer

    这些Buffer覆盖了你能通过IO发送的基本数据类型:byte, short, int, long, float, double 和 char。 

    Java NIO 还有个 Mappedyteuffer,用于表示内存映射文件。 

    Selector 

    Selector允许单线程处理多个 Channel。如果你的应用打开了多个连接(通道),但每个连接的流量都很低,使用Selector就会很方便。

    要使用Selector,得向Selector注册Channel,然后调用它的select()方法。这个方法会一直阻塞到某个注册的通道有事件就绪。一旦这个方法返回,线程就可以处理这些事件,事件的例子有如新连接进来,数据接收等。 

    通道(Channel)

    Java NIO的通道类似流,但又有些不同: 

    • 既可以从通道中读取数据,又可以写数据到通道。但流的读写通常是单向的。
    • 通道可以异步地读写。
    • 通道中的数据总是要先读到一个Buffer,或者总是要从一个Buffer中写入。

    正如上面所说,从通道读取数据到缓冲区,从缓冲区写入数据到通道。

    缓冲区(Buffer)

    数据是从通道读入缓冲区,从缓冲区写入到通道中的。 

    缓冲区本质上是一块可以写入数据,然后可以从中读取数据的内存。这块内存被包装成NIO Buffer对象,并提供了一组方法,用来方便的访问该块内存。 

    Buffer的基本用法 

    使用Buffer读写数据一般遵循以下四个步骤: 

    • 写入数据到Buffer
    • 调用flip()方法
    • 从Buffer中读取数据
    • 调用clear()方法或者compact()方法


    当向buffer写入数据时,buffer会记录下写了多少数据。一旦要读取数据,需要通过flip()方法将Buffer从写模式切换到读模式。在读模式下,可以读取之前写入到buffer的所有数据。 

    一旦读完了所有的数据,就需要清空缓冲区,让它可以再次被写入。有两种方式能清空缓冲区:调用clear()或compact()方法。clear()方法会清空整个缓冲区。compact()方法只会清除已经读过的数据。任何未读的数据都被移到缓冲区的起始处,新写入的数据将放到缓冲区未读数据的后面。 

    Buffer的capacity,position和limit 

    缓冲区本质上是一块可以写入数据,然后可以从中读取数据的内存。这块内存被包装成NIO Buffer对象,并提供了一组方法,用来方便的访问该块内存。 

    为了理解Buffer的工作原理,需要熟悉它的三个属性: 

    • capacity
    • position
    • limit


    position和limit的含义取决于Buffer处在读模式还是写模式。不管Buffer处在什么模式,capacity的含义总是一样的。 

    capacity 


    作为一个内存块,Buffer有一个固定的大小值,也叫“capacity”.你只能往里写capacity个byte、long,char等类型。一旦Buffer满了,需要将其清空(通过读数据或者清除数据)才能继续写数据往里写数据。 

    position 

    当你写数据到Buffer中时,position表示当前的位置。初始的position值为0.当一个byte、long等数据写到Buffer后, position会向前移动到下一个可插入数据的Buffer单元。position最大可为capacity – 1。 

    当读取数据时,也是从某个特定位置读。当将Buffer从写模式切换到读模式,position会被重置为0。当从Buffer的position处读取数据时,position向前移动到下一个可读的位置。 

    limit 

    在写模式下,Buffer的limit表示你最多能往Buffer里写多少数据。 写模式下,limit等于Buffer的capacity。 

    当切换Buffer到读模式时, limit表示你最多能读到多少数据。因此,当切换Buffer到读模式时,limit会被设置成写模式下的position值。换句话说,你能读到之前写入的所有数据(limit被设置成已写数据的数量,这个值在写模式下就是position) 

    向Buffer中写数据 

    写数据到Buffer有两种方式: 

    • 从Channel写到Buffer。
    • 通过Buffer的put()方法写到Buffer里。

    从Buffer中读取数据 

    从Buffer中读取数据有两种方式: 

      • 从Buffer读取数据到Channel。
      • 使用get()方法从Buffer中读取数据。

    NIO代码

    public void selector() throws IOException {
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            Selector selector = Selector.open();
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false);
            ssc.socket().bind(new InetSocketAddress(8080));
            ssc.register(selector, SelectionKey.OP_ACCEPT);
            while (true) {
                Set selectedKeys = selector.selectedKeys();
                Iterator it = selectedKeys.iterator();
                while (it.hasNext()) {
                    SelectionKey key = (SelectionKey) it.next();
                    if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
                        ServerSocketChannel ssChannel = (ServerSocketChannel) key.channel();
                        SocketChannel sc = ssChannel.accept();
                        sc.configureBlocking(false);
                        sc.register(selector, SelectionKey.OP_READ);
                    }
                    else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
                        SocketChannel sc = (SocketChannel) key.channel();
                        while (true) {
                            buffer.clear();
                            int n = sc.read(buffer);
                            if (n <= 0) {
                                break;
                            }
                            buffer.flip();
                        }
                    }
                    it.remove();
                }
            }
        }

    NIO FileChannel

    NIO提供了比传统的文件访问更好的访问方法,NIO有两个优化的方法:一个是 FIleChannel.transferTo FileChannel.transferFrom,另一个是FileChannel.map,均提供了数据在内核空间的直接移动,减少了内核空间和用户空间的复制损耗

    下面是FileChannel.map使用示例:

    复制代码
        public static void main(String[] args) {
            int BUFFER_SIZE = 1024;
            String filename = "teset.db";
            long fileLength = new File(filename).length();
            int bufferCount = 1 + (int) fileLength / BUFFER_SIZE;
            MappedByteBuffer[] buffers = new MappedByteBuffer[bufferCount];
            long remaining = fileLength;
            for (int i=0; i<bufferCount; i++) {
                RandomAccessFile file;
                try {
                    file = new RandomAccessFile(filename, "r");
                    buffers[i] = file.getChannel().map(FileChannel.MapMode.READ_ONLY, i*BUFFER_SIZE, (int) Math.min(remaining, BUFFER_SIZE));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                remaining -= BUFFER_SIZE;
            }
        }
    复制代码
  • 相关阅读:
    UVa Live 3942 Remember the Word
    UVa 11019 Matrix Matcher
    bzoj 4445 小凸想跑步
    Codeforces 832E Vasya and Shifts
    二值法方法综述及matlab程序
    排序算法(1)-插入,选择,冒泡
    如果我想了解一个陌生人
    Libsvm在matlab环境下使用指南
    科学预测世界杯-采用机器学习方法
    应用笔画宽度变换(SWT)来检测自然场景中的文本
  • 原文地址:https://www.cnblogs.com/m2492565210/p/7227238.html
Copyright © 2011-2022 走看看