×

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

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Java instance variable

An instance in object-oriented programming (OOP) is a particular implementation of any object. Each realized version of an item, which might vary in several ways, is an instance. Instantiation is...

3 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 minutes read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

Interleaving string in Java

If the string Str3 contains all of the characters from Str1 and Str2, it is considered interleaving Str1 and Str2. Keep in mind that the order of all characters in...

5 minutes read.

Java Math sqrt() Method

The sqrt() method of Java Math class returns the accurately rounded positive square root of the specified double value. Syntax: public static double sqrt(double a) Parameters: The parameter ‘a’ represents the number whose square...

2 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.

Java Math decrementExact() Method

The decrementExact() method of Math class returns the argument which is decremented by one, throwing an exception is the result overflows an int or long. Syntax: public static int decrementExact (int a) Parameters: The...

1 minute read.

Find the Frequency of Each Element in the Array in Java

We may count the occurrence of each element in the array of items. Maintaining one array to store the counts of each array element is one strategy for solving this issue....

3 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.

Various operations on the Queue using Stack in Java

The Java Collections Framework's core data structures are the Stack and Queue. They are used to store and retrieve identical data in a presentation sequence. These two linear data structures...

7 minutes read.

Java Integer divideUnsigned() method

The divideUnsigned() method of Integer class returns the unsigned quotient by dividing the first argument by the second argument. Syntax public static int divideUnsigned (int dividend , int divisor) Parameters The parameter ‘dividend’ represents...

1 minute read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept...

3 minutes read.

Java Integer longValue() method

The longValue()  method of Java Integer class returns a long value for this Integer after a widening primitive conversion. Syntax public long longValue() Parameters NA Specified by This method is specified by longValue in class Number Return...

1 minute read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 minutes read.