Home >Java >javaTutorial >FileChannel of JAVA-6NIO

FileChannel of JAVA-6NIO

巴扎黑
巴扎黑Original
2017-06-26 09:57:401341browse

FileChannel in Java NIO is a channel connected to a file. Files can be read and written through file channels.

FileChannel cannot be set to non-blocking mode, it always runs in blocking mode.

Open FileChannel

Before using FileChannel, you must open it first. However, we cannot open a FileChannel directly. We need to obtain a FileChannel instance by using an InputStream, OutputStream or RandomAccessFile.

Read data from FileChannel

Call one of the multiple read() methods to read data from FileChannel.

First, allocate a Buffer. Data read from FileChannel will be read into Buffer.

Then, call the FileChannel.read() method. This method reads data from FileChannel into Buffer. The int value returned by the read() method indicates how many bytes were read into the Buffer. If -1 is returned, it means the end of the file has been reached.

Write data to FileChannel

Use the FileChannel.write() method to write data to FileChannel. The parameter of this method is a Buffer.

Note that FileChannel.write() is called in a while loop. Because there is no guarantee how many bytes the write() method can write to the FileChannel at one time, the write() method needs to be called repeatedly until there are no bytes in the Buffer that have not been written to the channel.

Close FileChannel

FileChannel must be closed after use. For example:

FileChannel's position method

Sometimes it may be necessary to read/write data at a specific position of FileChannel. You can get the current position of FileChannel by calling the position() method.

You can also set the current position of FileChannel by calling the position(long pos) method.

If you set the position after the end of file and then try to read data from the file channel, the read method will return -1 - the end of file flag.

If you set the position after the end of the file and then write data to the channel, the file will be expanded to the current position and the data will be written. This can lead to "file holes", gaps between the data written in the physical files on the disk.

FileChannel's size method

The size() method of a FileChannel instance will return the size of the file associated with the instance. For example:

FileChannel's truncate method

You can use the FileChannel.truncate() method to intercept a file. When intercepting a file, the part after the specified length of the file will be deleted. For example:

This example intercepts the first 1024 bytes of the file.

FileChannel's force method

The FileChannel.force() method forces the data in the channel that has not yet been written to the disk to be written to the disk. For performance reasons, the operating system caches data in memory, so there is no guarantee that data written to FileChannel will be written to disk immediately. To ensure this, the force() method needs to be called.

The force() method has a boolean parameter, indicating whether to write file metadata (permission information, etc.) to the disk at the same time.

/** * file channel     */@Testpublic void text1() throws IOException {//从buffer读RandomAccessFile raf = new RandomAccessFile(new File("./test.txt"),"rw");
        FileChannel channel = raf.getChannel();             //获取通道channel.position(channel.size());                   //设置文件末尾位置,作为写入初始位置;不带参获取指针位置ByteBuffer byteBuffer = ByteBuffer.allocate(1024);  //缓冲区byteBuffer.put("456".getBytes());
        byteBuffer.flip();                                  //反转while (byteBuffer.hasRemaining()) {                 //判断            channel.write(byteBuffer);
        }
        channel.truncate(2);                                //截取文件channel.force(true);                      //强行写        raf.close();//向buffer写raf = new RandomAccessFile(new File("./test.txt"),"rw");
        channel = raf.getChannel();
        byteBuffer = ByteBuffer.allocate(1024);int read;while ((read = channel.read(byteBuffer))!=-1) {
            byteBuffer.flip();                                  //反转while (byteBuffer.hasRemaining()) {                 //判断System.err.print((char)byteBuffer.get());       //输出            }
            byteBuffer.clear();                                 //清除        }
    }

The above is the detailed content of FileChannel of JAVA-6NIO. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn