🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Copying a file is a common task that can be performed using various classes and methods in Java. This tutorial will demonstrate different ways to copy a file using standard Java I/O streams and the NIO (New I/O) package.
Table of Contents
- Introduction
- Using Java I/O Streams
- FileInputStream and FileOutputStream
- Using Java NIO
- Files.copy() Method
- Conclusion
Introduction
Copying a file involves reading data from the source file and writing it to the destination file. Java provides multiple ways to achieve this, including using traditional I/O streams and the NIO package introduced in Java 7, which provides more efficient and convenient methods for file operations.
Using Java I/O Streams
Using FileInputStream and FileOutputStream
The FileInputStream and FileOutputStream classes are used for reading and writing bytes. We can use these classes to copy a file byte by byte.
Example
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFileUsingIO {
public static void main(String[] args) {
String sourceFile = "source.txt";
String destinationFile = "destination.txt";
try (FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(destinationFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
System.out.println("File copied successfully using FileInputStream and FileOutputStream.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:
FileInputStreamis used to read bytes from the source file.FileOutputStreamis used to write bytes to the destination file.- A buffer of 1024 bytes is used to read and write data in chunks, improving performance.
- The
whileloop reads bytes from the source file and writes them to the destination file until the end of the file is reached.
Using Java NIO
Using Files.copy() Method
The NIO package provides a more efficient and convenient way to copy files using the Files.copy() method. This method is part of the java.nio.file.Files class and can be used to copy files with various options.
Example
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
public class CopyFileUsingNIO {
public static void main(String[] args) {
Path sourcePath = Paths.get("source.txt");
Path destinationPath = Paths.get("destination.txt");
try {
Files.copy(sourcePath, destinationPath);
System.out.println("File copied successfully using Files.copy().");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:
Paths.get()is used to obtain thePathobjects for the source and destination files.Files.copy()is used to copy the file from the source path to the destination path.- This method provides a simple and efficient way to copy files with less code.
Copying with Overwrite Option
If you want to overwrite the destination file if it already exists, you can use the StandardCopyOption.REPLACE_EXISTING option.
Example
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.io.IOException;
public class CopyFileWithOverwrite {
public static void main(String[] args) {
Path sourcePath = Paths.get("source.txt");
Path destinationPath = Paths.get("destination.txt");
try {
Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("File copied successfully with overwrite option.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:
StandardCopyOption.REPLACE_EXISTINGis used to specify that the existing destination file should be overwritten if it exists.- The
Files.copy()method copies the file from the source path to the destination path, overwriting the existing file if necessary.
Conclusion
Copying a file in Java can be accomplished using various methods, including traditional I/O streams and the NIO package. The FileInputStream and FileOutputStream classes provide a straightforward way to copy files byte by byte, while the NIO package's Files.copy() method offers a more efficient and convenient approach. By understanding these methods, you can choose the appropriate approach for copying files in your Java applications.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment