Copying Files using Java Code
In this Copying Files using Java application we will learn how to copy file using java code. I have used swings for creating a sample application which has progress bar to tell the progress of copying process. We are using simple java input stream and output stream to copy the file from one location to other location. You have to specify source location which is the file that user is copying. Then he/she has to specify destination location for the copied file, if both the locations are valid file will be copied.
Steps for copying File
- Enter source location.
- Enter Destination location.
- Click the button. If both the locations are valid file will be copied.
Snapshot for File copy Application
Source Code for Copy File Application
MainWindow.java
package com.projectsgeek; import com.projectsgeek.copy.CopyThread; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * * @author Projectsgeek.com */ public class MainWindow extends javax.swing.JFrame implements ActionListener{ /** * Creates new form MainWindow */ public MainWindow() { initComponents(); // Registering the action listner for button jButton1.addActionListener(this); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jProgressBar1 = new javax.swing.JProgressBar(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Copy File Application"); setPreferredSize(new java.awt.Dimension(500, 200)); jLabel1.setText("Source File"); jLabel2.setText("Destination File"); jButton1.setText("Copy"); jProgressBar1.setStringPainted(true); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(206, 206, 206) .addComponent(jButton1) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(28, 28, 28) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 119, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(31, 31, 31)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(27, 27, 27) .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold> /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see https://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainWindow().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JProgressBar jProgressBar1; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; // End of variables declaration // Catching the action event and the peforming the Task. This method will get executed when button is clicked. @Override public void actionPerformed(ActionEvent e) { // Creating a runnable for the task CopyThread copythread = new CopyThread(); // Setting the source file copythread.setSourceFile(jTextField1.getText()); // Setting the destination File copythread.setDestinationFile(jTextField2.getText()); // Setting the progress bar instance in runnable class copythread.setjProgressBar1(jProgressBar1); // Passing the runnable to thread Thread thread = new Thread(copythread); // Starting the thread thread.start(); } }
CopyThread.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.projectsgeek.copy; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.swing.JProgressBar; /** * * @author Projectsgeek.com */ public class CopyThread implements Runnable{ private String sourceFile; private String destinationFile; private javax.swing.JProgressBar jProgressBar1; // Setters and getters for sourceFile, destinationFile and progressbar public JProgressBar getjProgressBar1() { return jProgressBar1; } public void setjProgressBar1(JProgressBar jProgressBar1) { this.jProgressBar1 = jProgressBar1; } public String getSourceFile() { return sourceFile; } public String getDestinationFile() { return destinationFile; } public void setSourceFile(String sourceFile) { this.sourceFile = sourceFile; } public void setDestinationFile(String destinationFile) { this.destinationFile = destinationFile; } // This is the run method which will do the real task of copying the file as well as updating the progress bar based on the current status @Override public void run() { // Creating the input stream to read the file InputStream inputStream = null; // Creating the output stream to write the file OutputStream outputStream = null; try{ // creating an instance of source file File sourcefile =new File(sourceFile); // creating an instance of destination file File destinationfile =new File(destinationFile); // Now reading the file and loading it in inputstream inputStream = new FileInputStream(sourcefile); // Now pointing output stream to the destination file outputStream = new FileOutputStream(destinationfile); byte[] buffer = new byte[1024]; // Taking the length of source file for updating progress bar long size = sourcefile.length(); long count=0; int length; // Now we will start byte by byte to read the inputstream and passing it to outputstream while ((length = inputStream.read(buffer)) > 0){ outputStream.write(buffer, 0, length); count+=length; // Updating the progress bar in percentage jProgressBar1.setValue((int) (count*100/size)); jProgressBar1.setString((int) (count*100/size)+"%"); } // Now copied succesfully updating progress bar jProgressBar1.setValue(100); jProgressBar1.setString("Copied Successfully"); // Closing input as well as outputstream inputStream.close(); outputStream.close(); }catch(IOException e){ e.printStackTrace(); } } }
Leave a Reply