×

Java Programs

Java Practice

Java program to copy files

This program will copy files in Java.

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

Java File Handling Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.