Open In App

Copying file using FileStreams in Java

Last Updated : 18 Apr, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The main logic of copying a file is to read the file associated with FileInputStream variable and write the read contents into the file associated with FileOutputStream variable. We can copy a file from one location to another using FileInputStream and FileOutputStream classes in Java. Now before adhering forward let us discuss essential methods that will be used in the program. 

Method 1: read(): Reads a byte of data. Present in FileInputStream. 

Return type: An integer value 

Syntax: Other versions 

int read(byte[] bytearray

or

int read(byte[] bytearray, int offset, int length)

Method 2: write(int b): Writes a byte of data. Present in FileOutputStream

Syntax:

void write(byte[] bytearray)

or

void write(byte[] bytearray, int offset, int length)

Implementation: We will be creating two files named “demo.rtf” and “outputdemo.rtf” as another file where no content is there. Below is an image of the “demo.rtf” file as a sample input image.

  • First, we will create two objects of the File class, one referring to FileInputClass and the other for FileOutputStream Class.
  • Now we will create objects of FileInputStream class and FileOutputStream class prior to creating variables and assigning null to corresponding datatypes.
  • Pass respective objects of FileInputStream and FileOutputStream objects
  • Now using loops keep reading from a file and write it to another file using FileOuputStream using the read() and write() methods.

Tip: It is good practice to close the streams to avoid memory leakage.      

Example 1:

Java




// Java Program to Illustrate File InputStream and File
 
// Importing required classes
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating object of File class
        // Passing files from directory of local machine
        File file = new File(
            "/Users/mayanksolanki/Desktop/demo.rtf");
        File oFile = new File(
            "/Users/mayanksolanki/Desktop/outputdemo.rtf");
 
        // Now creating object of FileInputStream
        // Here they are variables
        FileInputStream fis = null;
        FileOutputStream fos = null;
 
        try {
            // Now we make them as objects of both classes
            // and passed reference of file in directory
            fis = new FileInputStream(file);
            fos = new FileOutputStream(oFile);
        }
 
        // Catch block to handle exceptions
        catch (FileNotFoundException e) {
 
            // Display message if exception occurs
            // File Not Found or Path is Incorrect
            System.out.println(e.printStackTrace());
        }
 
        try {
 
            // Now let us check how many bytes are available
            // inside content of file
            fis.available();
        }
 
        catch (Exception e) {
            e.printStackTrace();
        }
 
        // Using while loop to
        // write over outputdemo file
        int i = 0;
        while (i = fis.read() != -1) {
            fos.write(i);
        }
 
        // It will execute no matter what
        // to close connections which is
        // always good practice
        finally
        {
 
            // Closing the file connections
 
            // For input stream
            if (fis != null😉 {
                fis.clsoe();
            }
 
            // For output stream
            if (fos != null) {
                fos.close();
            }
        }
    }
}


Output: The same content will be reflected back in the “outputdemo.rtf” file as seen below in the “demo.rtf” file. 

Example 2:

Java




// Java Program Illustrating Copying a src File
// to Destination
 
// Importing required classes
import java.io.*;
 
// Main class
// src2dest
class GFG {
 
    // Main driver method
    public static void main(String args[])
        throws FileNotFoundException, IOException
    {
 
        // If file doesnot exist FileInputStream throws
        // FileNotFoundException and read() write() throws
        // IOException if I/O error occurs
        FileInputStream fis = new FileInputStream(args[0]);
 
        // Assuming that the file exists and
        // need not to be checked
        FileOutputStream fos
            = new FileOutputStream(args[1]);
 
        int b;
        while ((b = fis.read()) != -1)
            fos.write(b);
 
        // read() method will read only next int so we used
        // while loop here in order to read upto end of file
        // and keep writing the read int into dest file
        fis.close();
        fos.close();
    }
}


Output:

Output Explanation: The name of the src file and dest file must be provided using command line arguments where args[0] is the name of the source file and args[1] is the name of the destination file. 



Similar Reads

How to Execute SQL File with Java using File and IO Streams?
In many cases, we often find the need to execute SQL commands on a database using JDBC to load raw data. While there are command-line or GUI interfaces provided by the database vendor, sometimes we may need to manage the database command execution using external software. In this article, we will learn how to execute an SQL file containing thousand
5 min read
Different Ways to Copy Content From One File to Another File in Java
In Java, we can copy the contents of one file to another file. This can be done by the FileInputStream and FileOutputStream classes. FileInputStream Class It is a byte input stream class which helps in reading the bytes from a file. It provides different methods to read the data from a file. FileInputStream fin = new FileInputStream(filename); This
3 min read
Java Program to Read Content From One File and Write it into Another File
File handling plays a major role in doing so as the first essential step is writing content to a file. For this is one must know how to write content in a file using the FileWriter class. The secondary step is reading content from a file and print the same. For this, one must have good hands on File Reader class to do so. Now in order to read conte
5 min read
How to Convert a Kotlin Source File to a Java Source File in Android?
We use Android Studio to translate our Java code into Kotlin while transitioning from Java to Kotlin. But what if we need to convert a Kotlin file to its Java equivalent? We'll examine how to convert a Kotlin source file to a Java source file in this blog. Let's get this party started. Because of its interoperability with Java, Kotlin grew at an ex
2 min read
How to Extract File Extension From a File Path String in Java?
In Java, working with Files is common, and knowing how to extract file extensions from file paths is essential for making informed decisions based on file types. In this article, we will explore techniques for doing this efficiently, empowering developers to improve their file-related operations. Program to extract file extension from a file path S
5 min read
How to Create a File with a Specific File Attribute in Java?
In Java, you can create a file with specific File attributes such as read-only, hidden, or system attributes. This allows you to control the behavior and visibility of the file in the File system. In this article, we'll explore how to create a file with specific attributes in Java. In this article, we will learn to create a file with a specific fil
2 min read
Java Program to Extract Content from a Java's .class File
In this article, we are going to extract the contents of the Java class file using the Apache Tika library. Apache Tika is used for document type detection and content extraction from various file formats. It uses various document parsers and document type detection techniques to detect and extract data. It provides a single generic API for parsing
2 min read
java.nio.file.attribute.FileTime Class in Java
The java.nio.file.attribute.FileTime class is used to get a value representing this file's timestamp i.e, the time when this file was last modified, accessed, or created. Class Declaration: public final class FileTime extends Object implements Comparable<FileTime>Methods: MethodDescriptioncompareTo(FileTime other)This method compares the valu
2 min read
java.nio.file.SimpleFileVisitor Class in Java
The java.nio.file.SimpleFileVisitor Class is used to visit all the files in a directory and to re-throw I/O exceptions whenever an I/O error occurs. Class declaration : public class SimpleFileVisitor<T> extends Object implements FileVisitor<T>Constructor: protected SimpleFileVIsitor(): Creates a new object of SimpleFileVisitor class.Met
3 min read
java.nio.file.Paths Class in Java
java.nio.file.Paths class contains static methods for converting path string or URI into Path. Class declaration : public final class Paths extends ObjectMethods: MethodDescriptionget(String first, String... more) This method converts a path string, or a sequence of strings that when joined form a path string, to a Path. get(URI uri) This method co
2 min read
Practice Tags :