Copying file using FileStreams in Java

Java Programming Java8Object Oriented Programming

This example shows how to copy the contents of one file into another file using read & write methods of FileStreams classes.

Example

Live Demo

import java.io.*;

public class Main {
   public static void main(String[] args) throws Exception {
      BufferedWriter out1 = new BufferedWriter(new FileWriter("srcfile"));
      out1.write("string to be copied\n");
      out1.close();
      InputStream in = new FileInputStream(new File("srcfile"));
      OutputStream out = new FileOutputStream(new File("destnfile"));
      byte[] buf = new byte[1024];
      int len;

      while ((len = in.read(buf)) > 0) {
         out.write(buf, 0, len);
      }

      in.close();
      out.close();
      BufferedReader in1 = new BufferedReader(new FileReader("destnfile"));
      String str;

      while ((str = in1.readLine()) != null) {
         System.out.println(str);
      }
      in.close();
   }
}

Result

The above code sample will produce the following result.

string to be copied

The following is another simple example of copy one file into another file in java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class CopyExample {
   public static void main(String[] args) {
      FileInputStream ins = null;
      FileOutputStream outs = null;
      try {
         File infile =new File("C:\\Users\\TutorialsPoint7\\Desktop\\abc.txt");
         File outfile =new File("C:\\Users\\TutorialsPoint7\\Desktop\\bbc.txt");
         ins = new FileInputStream(infile);
         outs = new FileOutputStream(outfile);
         byte[] buffer = new byte[1024];
         int length;

         while ((length = ins.read(buffer)) > 0) {
            outs.write(buffer, 0, length);
         }          
         ins.close();
         outs.close();
         System.out.println("File copied successfully!!");
      } catch(IOException ioe) {
         ioe.printStackTrace();
      }    
   }
}

The above code sample will produce the following result.

File copied successfully!!
raja
Published on 23-Jul-2018 08:42:57
Advertisements