🌐
Oracle
docs.oracle.com › javase › tutorial › essential › io › file.html
Reading, Writing, and Creating Files (The Java™ Tutorials > Essential Java Classes > Basic I/O)
Path file = ...; byte[] fileArray; fileArray = Files.readAllBytes(file); You can use one of the write methods to write bytes, or lines, to a file. ... The following code snippet shows how to use a write method. Path file = ...; byte[] buf = ...; Files.write(file, buf); The java.nio.file package ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › read-and-write-files-using-the-new-i-o-nio-2-api-in-java
How to Read and Write Files Using the New I/O (NIO.2) API in Java? - GeeksforGeeks
March 18, 2024 - After that, we get path information about the target file by using Path class available in java.nio package. Here our target file is example.txt. Next in try catch block, we have taken some String values as a list because the write method takes byte array only. Then perform write operation by using Files.write(). In this example, we can read existing data from the example.txt using Files.readAllLines().
🌐
Javapapers
javapapers.com › java › java-nio-file-read-write-with-channels
Java NIO File Read Write with Channels - Javapapers
(); options.add(StandardOpenOption.CREATE); options.add(StandardOpenOption.APPEND); Path path = Paths.get("./byFileChannel.txt"); FileChannel fileChannel = FileChannel.open(path, options); fileChannel.write(byteBuffer); fileChannel.close(); } package com.javapapers.java.nio; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SeekableByteChannel; import java.nio.charset.Charset; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Pa
🌐
Medium
medium.com › @vusal.guliyev.313 › writing-files-with-nio-and-io-in-java-bc60b06a413a
Writing Files with NIO and IO in Java | by Vusal Guliyev | Medium
February 9, 2024 - Writing Files with NIO and IO in Java (Continued): In addition to the examples provided above, developers can leverage both NIO and traditional IO APIs for various file writing tasks. Here are additional examples demonstrating file writing using both NIO and IO: ... // Writing an object to a file with NIO public static void writeObjectToFile(Object obj, String objectFile) throws Exception { try (ObjectOutputStream oos = new ObjectOutputStream(Files.newOutputStream(Paths.get(objectFile)))) { oos.writeObject(obj); oos.flush(); } } // Writing text to a file with NIO public static void writeTextToFile(String message) throws IOException { Path filePath = Paths.get("file.txt"); Files.write(filePath, message.getBytes(), StandardOpenOption.CREATE); }
🌐
Attacomsian
attacomsian.com › blog › java-read-write-files-nio-api
Reading and Writing Files using Java NIO API
December 6, 2019 - To write a text, you can use the ... there!\nWhat's up?"; // write to file Files.write(Paths.get("output.txt"), contents.getBytes()); } catch (IOException ex) { ex.printStackTrace(); } With Files.write(), you can also specify ...
🌐
TutorialsPoint
tutorialspoint.com › java_nio › java_nio_file.htm
Java NIO - File
package com.java.nio; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class ReadFile { public static void main(String[] args) { Path wiki_path = Paths.get("D:file.txt"); Charset charset = Charset.forName("ISO-8859-1"); try { List<String> lines = Files.readAllLines(wiki_path, charset); for (String line : lines) { System.out.println(line); } } catch (IOException e) { System.out.println(e); } } } Welcome to file. size(Path path) − This method is used to get the size of t
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java
Java Nio Read File Example - Java Code Geeks
November 9, 2023 - Download You can download the full source code of this example here: NIO API Read File Example · Do you want to know how to develop your skillset to become a Java Rockstar?
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › nio › file
Java Nio Write File Example - Java Code Geeks
March 12, 2019 - This was an example of writing to a file with Java NIO2 API. Download You can download the full source code of this example here: Java Nio Write File Example
🌐
Vogella
vogella.com › tutorials › JavaIO › article.html
Reading and writing files in Java (Input/Output) - Tutorial
February 26, 2026 - package com.vogella.java.files; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; public class Main { public static void main(String[] args) throws IOException { String input = FilesUtil.readTextFile("file.txt"); System.out.println(input); FilesUtil.writeToTextFile("copy.txt", input); System.out.println(FilesUtil.readTextFile("copy.txt")); FilesUtil.readTextFileByLines("file.txt"); Path path = Paths.get("file.txt"); } }
Find elsewhere
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-files-nio-files-class
Java Files - java.nio.file.Files Class | DigitalOcean
August 4, 2022 - package com.journaldev.examples; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * Java Files write file example * * @author pankaj * */ public class FilesWriteFileExample { public static void main(String[] args) { Path path = Paths.get("D:/data/test.txt"); try { String str = "This is write file Example"; byte[] bs = str.getBytes(); Path writtenFilePath = Files.write(path, bs); System.out.println("Written content in file:\n"+ new String(Files.readAllBytes(writtenFilePath))); } catch (Exception e) { e.printStackTrace(); } } }
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › nio › file › Files.html
Files (Java Platform SE 7 )
Usage Example: Suppose we want to set the last modified time to the current time: Path path = ... FileTime now = FileTime.fromMillis(System.currentTimeMillis()); Files.setLastModifiedTime(path, now); ... SecurityException - In the case of the default provider, the security manager's checkWrite ...
Top answer
1 of 2
2

Note that you can simply use Files.copy(Paths.get(inFileStr),Paths.get(outFileStr), StandardCopyOption.REPLACE_EXISTING) to copy the file as your example code does, just likely faster and with only one line of code.

Otherwise, if you already have opened the two file channels, you can just use
in.transferTo(0, in.size(), out) to transfer the entire contents of the in channel to the out channel. Note that this method allows to specify a range within the source file that will be transferred to the target channel’s current position (which is initially zero) and that there’s also a method for the opposite way, i.e. out.transferFrom(in, 0, in.size()) to transfer data from the source channel’s current position to an absolute range within the target file.

Together, they allow almost every imaginable nontrivial bulk transfer in an efficient way without the need to copy the data into a Java side buffer. If that’s not solving your needs, you have to be more specific in your question.

By the way, you can open a FileChannel directly without the FileInputStream/FileOutputStream detour since Java 7.

2 of 2
1
while ((bytesCount = in.read(bytebuf)) > 0) { 
        // flip the buffer which set the limit to current position, and position to 0.
        bytebuf.flip();
        out.write(bytebuf); // Write data from ByteBuffer to file
        bytebuf.clear(); // For the next read
    }

Your copy loop is not correct. It should be:

while ((bytesCount = in.read(bytebuf)) > 0 || bytebuf.position() > 0) { 
        // flip the buffer which set the limit to current position, and position to 0.
        bytebuf.flip();
        out.write(bytebuf); // Write data from ByteBuffer to file
        bytebuf.compact(); // For the next read
    }

Can anybody tell, should I follow the same procedure if my file size [is] more than 2 GB?

Yes. The file size doesn't make any difference.

🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › nio › file › Files.html
Files (Java Platform SE 8 )
April 21, 2026 - Usage Example: Suppose we want to set the last modified time to the current time: Path path = ... FileTime now = FileTime.fromMillis(System.currentTimeMillis()); Files.setLastModifiedTime(path, now); ... SecurityException - In the case of the default provider, the security manager's checkWrite ...
🌐
TutorialsPoint
tutorialspoint.com › java_nio › java_nio_file_channel.htm
Java NIO - File Channel
import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.HashSet; import java.util.Set; public class FileChannelDemo { public static void main(String args[]) throws IOException { //append the content to existing file writeFileChannel(ByteBuffer.wrap("Welcome to TutorialsPoint".getBytes())); //read the file readFileChannel(); } public static void readFileChannel() throws IOException
🌐
Cleverence
cleverence.com › articles › oracle-documentation › reading-writing-creating-files-the-java-tutorials-4281
Java File I/O Guide: Reading, Writing, and Creating Files with NIO.2
January 26, 2026 - Master Java file I/O using java.io and NIO.2: read, write, create, copy, move, watch, and secure files. Practical code, patterns, performance tips, and enterprise use cases.
🌐
How to do in Java
howtodoinjava.com › home › java new input/output › reading a file with channels and buffers
Reading a File with Channels and Buffers
April 12, 2022 - Hi Lokesh, thanks for the informative write-up. The key difference is that in NIO you are reading a buffer not a stream. And NIO is by design non-blocking. So the thread is not blocked. Reply · Just a question. I have to process huge text files (billions of records, each) line by line. Should I read them with IO, NIO, or NIO2? Which class? Reply · IO is not good solution. Use ReadFileWithFixedSizeBuffer example. In java 8, you can use https://howtodoinjava.com/java8/read-file-line-by-line/ Reply
🌐
LinkedIn
linkedin.com › pulse › reading-writing-files-java-nio-michaela-prehofer
Reading and Writing Files in Java NIO - Michaela Prehofer
October 15, 2020 - Methods designed for the common cases of reading the entire content of a file in one pass e.g., readdAllBytes, readAllLines, and their corresponding write counterparts. These methods should be used only for operating on small files.
🌐
Jenkov
jenkov.com › tutorials › java-nio › file-channel.html
Java NIO FileChannel
March 11, 2021 - You need to obtain a FileChannel ... FileChannel via a RandomAccessFile: RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw"); FileChannel inChannel = aFile.getChannel();...