Q:

Java program to copy files

belongs to collection: Java File Handling Programs

0

This program will copy files in Java.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Copy Files using Java Program

// Java program to copy file

import java.io.*;

public class FileCopy {
  public static void main(String args[]) {
    try {
      //input file
      FileInputStream sourceFile = new FileInputStream(args[0]);
      //output file
      FileOutputStream targetFile = new FileOutputStream(args[1]);

      // Copy each byte from the input to output
      int byteValue;
      //read byte from first file and write it into second line
      while ((byteValue = sourceFile.read()) != -1)
        targetFile.write(byteValue);

      // Close the files!!!
      sourceFile.close();
      targetFile.close();

      System.out.println("File copied successfully");
    }
    // If something went wrong, report it!
    catch (IOException e) {
      System.out.println("Exception: " + e.toString());
    }
  }
}

Output:

    
Compile: javac FileCopy.java
Run: java FileCopy file1.txt file2.txt
    
File copied successfully

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java File Handling Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to get the last modification date and... >>
<< Java program to delete a file...