search
HomeJavajavaTutorialFileChannel of JAVA-6NIO
FileChannel of JAVA-6NIOJun 26, 2017 am 09:57 AM

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
How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

How can I implement functional programming techniques in Java?How can I implement functional programming techniques in Java?Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I use Java's NIO (New Input/Output) API for non-blocking I/O?How do I use Java's NIO (New Input/Output) API for non-blocking I/O?Mar 11, 2025 pm 05:51 PM

This article explains Java's NIO API for non-blocking I/O, using Selectors and Channels to handle multiple connections efficiently with a single thread. It details the process, benefits (scalability, performance), and potential pitfalls (complexity,

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I use Java's sockets API for network communication?How do I use Java's sockets API for network communication?Mar 11, 2025 pm 05:53 PM

This article details Java's socket API for network communication, covering client-server setup, data handling, and crucial considerations like resource management, error handling, and security. It also explores performance optimization techniques, i

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft