Use RandomAccessFile read the file

A, RandomAccessFile Introduction 

    1. Direct source RandomAccessFile see, Examples of commonly used methods are:

     1) pass the filename and mode of access to the file, mode for the access to the files

  public RandomAccessFile(String name, String mode)
        throws FileNotFoundException
     {
        this(name != null ? new File(name) : null, mode);
     }

      

    2) the object and the incoming file permissions, when the definition file defines some flag with constant access.

  private static final int O_RDONLY = 1;
    private static final int O_RDWR =   2;
    private static final int O_SYNC =   4;
    private static final int O_DSYNC =  8;  

 

    public RandomAccessFile(File file, String mode)
        throws FileNotFoundException
    {
        String name = (file != null ? file.getPath() : null);
        int imode = -1;
        if (mode.equals("r"))
            imode = O_RDONLY; // 1
        else if (mode.startsWith("rw")) {
            imode = O_RDWR;
            rw = true;
            if (mode.length() > 2) {
                if (mode.equals("rws"))
                    imode |= O_SYNC;   //4
                else if (mode.equals("rwd"))
                    imode |= O_DSYNC; //8
                else
                    imode = -1;
            }
        }
        if (imode < 0)
            throw new IllegalArgumentException("Illegal mode \"" + mode
                                               + "\" must be one of "
                                               + "\"r\", \"rw\", \"rws\","
                                               + " or \"rwd\"");
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkRead(name);
            if (rw) {
                security.checkWrite(name);
            }
        }
        if (name == null) {
            throw new NullPointerException();
        }
        if (file.isInvalid()) {
            throw new FileNotFoundException("Invalid file path");
        }
        fd = new FileDescriptor();
        fd.attach(this);
        path = name;
        open(name, imode);
    }

 3) parameter mode Introduction

     r: indicates that the file read-only.

     rw: indicates that the file is readable and writable.

     rws: indicates that the file supports synchronization of readable and writable.

     rwd: indicates that the file does not support synchronization of readable and writable.

 

2. RandomAccessFile class conventional method described

    1) public int read (byte b []); read method in a byte stream file read out and the array of bytes to access.

    2) public native long getFilePointer () throws IOException; getFilePoint method for reading the file pointer is located at which position the current file.

    3) public void seek (long pos) throws IOException; seek ways to move the file pointer to a specified location.

    4) public native long length () throws IOException; method of acquiring the total length of the file length.

 

 

3. Use Case

      The login user name and password used to store the file .dat, user name and password length is 32 bytes, 100 bytes per line .dat file.

    1) Registration

  / *
         * Write information to the register file user.dat
         * 100 bytes occupied by each record, wherein, the user name, the password, the nickname character string
         * 32 bytes of the occupation, age int value 4 bytes
         * 
         * /
        the try (a RandomAccessFile Raf a RandomAccessFile new new = ( "User.dat", "RW");) {
              raf.seek (raf.length ());
                byte [] = username.getBytes Data ( "UTF-. 8") ;
                data = Arrays.copyOf (data, 32);
                raf.write (data); // write data to a file
                data = password.getBytes ( "UTF-. 8");
                data = Arrays.copyOf (data, 32 );
                raf.write (Data);
                Data = nickname.getBytes ( "UTF-. 8");
                Data = Arrays.copyOf (Data, 32);
                raf.write(data);
                data=request.getParameter("age").getBytes("UTF-8");
                data=Arrays.copyOf(data, 4);
                raf.write(data);
        } catch (Exception e) {
            e.printStackTrace();
        }

 

    2) Log

       Read .dat file, extract the username and password with the username and password passed match, reading row by row, if not read, the pointer moves to the next line.

    try (RandomAccessFile raf=new RandomAccessFile("user.dat","r");){
            String username=request.getParameter("username");
            System.out.println("username:"+username);
            String password=request.getParameter("password");
            System.out.println("password:"+password);
            boolean flag=false;
            for(int i=0;i<raf.length()/100;i++) {
                //读取第0-32个字节和32-64个字节与username 和password进行比较
                byte[]data=new byte[32];
                raf.read(data);
                String user_name=new String(data,"utf-8").trim();
                raf.read(data);
                String pass_word=new String(data,"utf-8").trim();
                IF (!! = null && username password = null) {
                IF (username.equals (user_name) && password.equals (pass_word)) {
                    // successful login
                    Flag = to true;
                    response.setEntity (new new File ( "webapps / myweb / login_success.html "));
                    System.out.println (" successful login ");!
                    BREAK;
                } the else {
                    raf.seek (100 + 100 * I);
                    Continue;
                }
            } the else {
                System.out.println (" user name and password empty ");!
            }
            }
            IF (In Flag) {!
                response.setEntity (new new File ( "the webapps / MyWeb / login_fail.html"));
                System.out.println ( "Sorry, incorrect login failed input!!");
            }
        } the catch (Exception E) {
            e.printStackTrace ( );
        }

 

 

Published 53 original articles · won praise 45 · views 8851

Guess you like

Origin blog.csdn.net/qq_33036061/article/details/104107923