×

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods leveraged in the process.

The content of one file can be copied to another file in Java. The FileInputStream as well as FileOutputStream classes are designed to handle this.

FileInputStream

One of the most popular and significant byte input stream class in Java is FileInputStream. It is mostly used to read data bytes from files. There are numerous methods available in the FileInputStream class for retrieving data from files.

The following syntax creates a new instance of a FileInputStream class:

FileInputStream f = new FileInputStream(file name);

The method constructor receives the file name that we want to retrieve data from. For replication of data from a file to another, we should use following two FileInputStream class methods.

  • read()
  • close()

read()

When extracting data from the file, the read() method is crucial. When its pointer approaches the file's end, it returns -1 and returns bytes of data as an integer.

close()

The FileInputStream class instance is closed using the close() function.

FileOutputSream

One of the most popular and significant byte output stream classes within Java is FileOutputStream. It is mostly employed to write bytes of data into files. There are numerous methods for transmitting the data into the file provided by the FileOutputStream class.

The following procedure is used to generate a FileOutputStream class instance:

FileOutputStream f= new FileOutputStream(file name)

The method constructor receives the file name that we wish to write data to. For replication of data of one file to another, we should use following two FileOutputStream class methods.

  • write()
  • close()

write()

When writing data (bytes of data) into the file, the write() method is crucial.

close()

The FileOutputStream class instance is closed using the close() function.

File

When writing or reading bytes of data from a file, the File class is employed to build an object of the file. The process used to generate a File class instance is as follows:

File fileobj = new File(file name);

Note: The File class shall generate a new file with the specified name if it does not already exist.

Let us understand how all of this will contribute to the replication pf data from one file to another.

File name: Copydata.java

import java.io.*;
import java.util.*;
public class CopyFromFileaToFileb {

public static void copyContent(File a, File b)
throws Exception
{
FileInputStream in = new FileInputStream(a);
FileOutputStream out = new FileOutputStream(b);


try {


int n;


// read() method to obtain the data from the given file
while ((n = in.read()) != -1) {
// write() method to retrieve the data to another file
out.write(n);
}
}
finally {
if (in != null) {


// close() method is used to close the stream
in.close();
}
// close() method is used to close the stream
if (out != null) {
out.close();
}
}
System.out.println("File Copied");
}


public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(System.in);


// obtains the name of the source file
System.out.println(
"Enter the name of the source file from which you wanted to copy the content or simply paste the file name :");
String a = sc.nextLine();


//to take source file
File s = new File(a);


// to get the file destination file
System.out.println(
"Enter the name of the destination file in which you want to copy the data or simply paste the file name :");
String b = sc.nextLine();


// to produce the destination file
File d = new File(b);


// method invoked to copy the data from the file 
copyContent(s, d);
}
}

Output:

Enter the source filename from where you have to read/copy :
source.txt
Enter the destination filename where you have to write/paste :
Destination.txt
File Copied

Before running the above program.

Copy data/content from one file to another file in java

This is the screenshot of the source file with some text inside it.

This is the screenshot of the destination file with no content in it and before running the above program.

Copy data/content from one file to another file in java

After successfully executing the above program.

This is the screenshot of the source file after running the program with some text in it.

Copy data/content from one file to another file in java

This is the screenshot of the destination file with copied content from the source file

Copy data/content from one file to another file in java

Related Topics

Split the Number String into Primes in Java

Given is a string that only contains digits and serves to represent a number. Our goal is to split the string of numbers in a way that ensures each segment...

2 minutes read.

Interfaces and Classes in Strings in Java

CharBuffer: CharBuffer is utilized to implement the CharSequence interface. With the help of the mentioned class, we can allow character buffers to be utilized instead of CharSequences. We can consider the illustration...

4 minutes read.

How to Convert Decimal to Binary in Java

How to Convert Decimal to Binary in Java There are two methods to convert Decimal to Binary. Using toBinaryString() method Using user-defined logic Using Integer.toBinaryString() The toBinaryString() is a static method of Integer...

2 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

Sorting Program in Java

Sorting Program in Java: The sorting program in Java is used to sort arrays either in ascending or descending order.  There are two predefined methods available in Java that are...

6 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

Java Break Keyword

Break: The word Break is a keyword or a statement in a java programming language.This Keyword break is used to stop the execution of the loop or switch statements etc.The loop...

3 minutes read.

Java Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.

Java Boolean Class

The Boolean class wraps a value of the Boolean primitive in an object. Its object contains only a single field whose type is Boolean. Boolean Methods: This class contains several different methods...

2 minutes read.

Concurrent Linked Deque in Java with Examples

Introduction Java's concurrent-linked deque, which holds its items as linked nodes, is unconstrained and thread-safe. Concurrent Linked Deque allows for element removal and addition on both sides because it implements the...

4 minutes read.

Java While Loop

A while loop is used to repeatedly execute a set of statements as long as its condition evaluates to true. This loop checks the condition before it starts the execution...

1 minute read.

How annotations work in Java

Annotations were introduced by sun microsystem and are available from the java 1.5 version. In general, configurations can be done either by XML or by annotations. Hibernate and spring framework users prefer...

4 minutes read.

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

Java Create File

A File is a hypothetical way, which has no genuine presence. It is very much like while "using" that File that the major real activity of putting away something in...

5 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

Java Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer...

3 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.