Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java java.nio.file.Files newByteChannel() Method

Java java.nio.file.Files.newByteChannel() Method

Java File Java java.nio.file.Files


newByteChannel() The method is used to open or create a file and returns a SeekableByteChannel object that can be used to read and write file content. This method is more flexible than the traditional FileInputStream and FileOutputStream because it supports random access to files (seek operations).

Method Definition

public

static

SeekableByteChannel newByteChannel

(

Path path, OpenOption...

options

)

throws

IOException

Parameter Description

  1. path - The path of the file to open or create
  2. options - Options specifying how to open the file (variable arguments)

Detailed explanation of OpenOption options

OpenOption is an interface, and its most commonly used implementation is the StandardOpenOption enum, which provides the following commonly used options:

Option Description
READ Open the file in read-only mode
WRITE Open the file in write mode
APPEND Open the file in append mode (used together with WRITE)
TRUNCATE_EXISTING If the file already exists, truncate it to 0 bytes
CREATE Create a new file if it does not exist
CREATE_NEW Create a new file, failing if the file already exists
DELETE_ON_CLOSE Delete the file when the channel is closed
SPARSE Sparse file hint
SYNC Require every write to be synchronized to the storage device
DSYNC Require every write to be synchronized to the storage device (file content only)

Usage examples

Example 1: Basic read and write operations

Example

import

java.nio.ByteBuffer

;

import

java.nio.channels.SeekableByteChannel

;

import

java.nio.file.*

;

import

java.util.EnumSet

;

public

class

ByteChannelExample

{

   

public

static

void

main

(

String

[

]

args

)

{

        Path path

=

Paths.

get

(

"example.txt"

)

;

       

       

try

(

SeekableByteChannel channel

=

Files.

newByteChannel

(

                path,

                EnumSet.

of

(

StandardOpenOption.

CREATE

, StandardOpenOption.

WRITE

)

)

)

{

           

           

// Write data

           

String

data

=

"Hello, Java NIO!"

;

            ByteBuffer buffer

=

ByteBuffer.

wrap

(

data.

getBytes

(

)

)

;

            channel.

write

(

buffer

)

;

           

           

// Reset position to the beginning of the file

            channel.

position

(

0

)

;

           

           

// Read data

            buffer.

clear

(

)

;

            channel.

read

(

buffer

)

;

            buffer.

flip

(

)

;

           

           

byte

[

]

bytes

=

new

byte

[

buffer.

remaining

(

)

]

;

            buffer.

get

(

bytes

)

;

           

System

.

out

.

println

(

new

String

(

bytes

)

)

;

           

       

}

catch

(

IOException

e

)

{

            e.

printStackTrace

(

)

;

       

}

   

}

}

Example 2: Random access file

Example

import

java.nio.ByteBuffer

;

import

java.nio.channels.SeekableByteChannel

;

import

java.nio.file.*

;

import

java.util.EnumSet

;

public

class

RandomAccessExample

{

   

public

static

void

main

(

String

[

]

args

)

{

        Path path

=

Paths.

get

(

"random.txt"

)

;

       

       

try

(

SeekableByteChannel channel

=

Files.

newByteChannel

(

                path,

                EnumSet.

of

(

StandardOpenOption.

CREATE

,

                          StandardOpenOption.

READ

,

                          StandardOpenOption.

WRITE

)

)

)

{

           

           

// Write data at the beginning of the file

            ByteBuffer buffer

=

ByteBuffer.

wrap

(

"ABCDEFGHIJ"

.

getBytes

(

)

)

;

            channel.

write

(

buffer

)

;

           

           

// Jump to position 4 and modify the data

            channel.

position

(

4

)

;

            buffer

=

ByteBuffer.

wrap

(

"1234"

.

getBytes

(

)

)

;

            channel.

write

(

buffer

)

;

           

           

// Read the entire file

            channel.

position

(

0

)

;

            buffer

=

ByteBuffer.

allocate

(

(

int

)

channel.

size

(

)

)

;

            channel.

read

(

buffer

)

;

            buffer.

flip

(

)

;

           

           

byte

[

]

bytes

=

new

byte

[

buffer.

remaining

(

)

]

;

            buffer.

get

(

bytes

)

;

           

System

.

out

.

println

(

new

String

(

bytes

)

)

;

 

// Output: ABCD1234IJ

           

       

}

catch

(

IOException

e

)

{

            e.

printStackTrace

(

)

;

       

}

   

}

}


Notes

  1. Resource management:SeekableByteChannel implements the AutoCloseable interface; it is recommended to use the try-with-resources statement to ensure the channel is closed properly.
  2. Thread Safety:SeekableByteChannel instances are generally not thread-safe and require synchronization when accessed by multiple threads.
  3. Performance considerations: For large file operations, consider using a buffer to improve performance.
  4. Exception handling: Be careful to handle the possible IOException, such as file not found, insufficient permissions, etc.

Comparison with traditional I/O

Feature newByteChannel() Traditional I/O (FileInputStream/FileOutputStream)
random access Supported Not supported
Simultaneous read and write Supported Not supported
Performance Usually higher Usually lower
Flexibility High Low
Ease of Use Lower Higher

Summary

Files.newByteChannel() The method provides a more powerful and flexible way to operate files than traditional I/O, and is especially suitable for scenarios that require random access or simultaneous read and write of files. Although its use is slightly more complex, the performance benefits and functional flexibility it brings make it an advanced choice for handling file I/O.

For simple file operations, traditional I/O may be easier to use; but for applications that require high performance or complex file operations,newByteChannel() is the better choice.

Java File Java java.nio.file.Files