Skip to main content

Using java to for file copy function interface

 File copy program

Purpose:

1. 1. Familiar with the writing of Swing interface;

2.2. Learn to use the JFileChooser file selector;

3.Learn to use file input stream FileInputStream and output stream FileOutputStream to copy files.

Content:

Use Swing basic components and a suitable layout manager to write the file copy program interface, use the JFileChooser file selector to realize the graphical operation of the source file and the target path, the specific operation flow of the file copy program is as follows:

(1) The main interface of the program operation

(2) Click the "Browse" button to pop up the file selection interface, select the source file to be copied

(3) In the same way, select the target path, and then click "Start Copy" to complete the file copy

Additional function: On the basis of the completion of the above functions, the file copy progress bar function can be added.

code show as below:


import java.awt.Color;

import java.awt.EventQueue;

import java.awt.GridLayout;

import java.awt.Toolkit;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import javax.swing.JButton;

import javax.swing.JFileChooser;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JProgressBar;

import javax.swing.JTextField;

import javax.swing.UIManager;

import javax.swing.UnsupportedLookAndFeelException;


public class Copy_Frame extends JFrame 

//implements Runnable 

{

//Create widget

JProgressBar progressbar;

JLabel jl1 = new JLabel("Source File:");

JTextField jtf1 = new JTextField(25);

JButton jb1 = new JButton("Browse");

JLabel jl2 = new JLabel("Target path:");

JTextField jtf2 = new JTextField(25);

JButton jb2 = new JButton("Browse");

JButton copyjb = new JButton("Start copying");

JLabel copylbed=new JLabel("Copy completed");

//Constructor

public Copy_Frame() {

try {

//The interface is set to Windows style

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

} catch (ClassNotFoundException | InstantiationException | IllegalAccessException

| UnsupportedLookAndFeelException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

    //Create progress bar

   progressbar = new JProgressBar();

// Display current progress value information

progressbar.setStringPainted(true);

// Set the progress bar border not to display

progressbar.setBorderPainted(false);

// Set the foreground color of the progress bar

progressbar.setForeground(new Color(0, 210, 40));

// Set the background color of the progress bar

progressbar.setBackground(new Color(188, 190, 194));

//Set the size of the progress bar

progressbar.setBounds(0,270,500,30);

//Set window properties

this.setTitle("File copy program");

this.setLayout(new GridLayout(5, 1));

this.setSize(500, 300);

this.setLocationRelativeTo(null);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Copied file control

JPanel jp1 = new JPanel();

jp1.add(jl1);

jp1.add(jtf1);

jp1.add(jb1);

this.add(jp1);

jb1.addMouseListener(new ButtonListener());

        //Copy file control

JPanel jp2 = new JPanel();

jp2.add(jl2);

jp2.add(jtf2);

jp2.add(jb2);

this.add(jp2);

jb2.addMouseListener(new ButtonListener());

        //Start copying controls

JPanel jp3 = new JPanel();

jp3.add(copyjb);

this.add(jp3);

copyjb.addMouseListener(new ButtonListener());//Set up the listener

this.add(progressbar);

//Progress bar control

JPanel jp4 = new JPanel();

jp4.add(progressbar);

this.add(jp4);

progressbar.setVisible(false);//Hide progress bar

//Copy complete button control

JPanel jp5= new JPanel();

jp5.add(copylbed);

this.add(jp5);

copylbed.setVisible(false);//Hidden text

}

//Use internal classes for file selection

class ButtonListener extends MouseAdapter{

@Override

public void mouseClicked(MouseEvent e) {

//Click to start copying

JFileChooser jc = new JFileChooser();

//If you click to start copying

if(e.getSource()==copyjb) {

progressbar.setVisible(true);//Show progress bar

//Start a new thread, start copying, and the progress bar starts to load

new Thread(new Runnable() {

@Override

public void run() {

// TODO Auto-generated method stub

try {

copying(jtf1.getText(),jtf2.getText());

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}).start();

}

//Click the "Browse" setting path of the file to be copied

if(e.getSource()==jb1) {

int val = jc.showOpenDialog(null);

if (val==JFileChooser.APPROVE_OPTION){//Determine whether to select the file

String copyFromFilePath1 = jc.getSelectedFile().getAbsolutePath();//Print file path

System.out.println(copyFromFilePath1);//The output file path is in the console

jtf1.setText(copyFromFilePath1);//Set the value of the text box to the file path to be copied

}

else{

System.out.println("No files selected!");//No file selected

}

}

//Click the "Browse" setting path of the file to be copied

if(e.getSource()==jb2) {

jc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//Only select the current file and its directory, do not enter the file

int val=jc.showOpenDialog(null);

if(val==JFileChooser.APPROVE_OPTION) {//Determine whether to select the file path

String copyFromFilePath2=jc.getSelectedFile().getAbsolutePath();//Print file path directory

System.out.println(copyFromFilePath2);//The output file path is in the console

jtf2.setText(copyFromFilePath2);//Set the value of the text box to the file path to be copied

}

else{

System.out.println("No files selected!");//No file selected

}

}

}

}

public void copying(String copy,String be_copyed) throws IOException {//Copy method

FileInputStream in  = new FileInputStream(copy);//File input stream

//Create a file object

File f=new File(copy);

//Add the copied file name after the destination

FileOutputStream out  = new FileOutputStream(be_copyed+"\\"+f.getName());

//Splicing, add the file name after the directory, indicating where to copy this file

byte[] b = new byte[1024];//Set the cache array, cache 1024 bytes each time

int n;//The number of bytes in the current loop buffer

long k;//Number of times to cache

k=f.length()/1024+1;

long j=k/100;//The number of times the progress bar needs to be cached for every 1%

long y=j;//Set initial value

long i=0;

int p=0;

int x=0;

//run();

//nIs the number of bytes in the file

while ((n=in.read(b))!=-1){

out.write(b,0,n);

i++;//Cache times

if(i==j)

{

j+=y;//The number of times the progress bar needs to be cached for the next load

p++;//The value of the progress bar

progressbar.setValue(p);//Set the current value of the progress bar

System.out.println("File copy current progress"+p+"%");

if(p==100)

{

copylbed.setVisible(true);//Pop-up copy completed label

}

}

}

//Close file input and output stream

in.close();

out.close();

System.out.println("File copy completed!");

}

public static void main(String[] args) {

Copy_Frame ad = new Copy_Frame();

ad.setVisible(true);

}

//JOptionPane.showMessageDialog(this, "Loading completed");

//this.dispose();Close the window and release resources

//this.pack();Fit the control to the window

}

Comments

Popular posts from this blog

Defination of the essential properties of operating systems

Define the essential properties of the following types of operating sys-tems:  Batch  Interactive  Time sharing  Real time  Network  Parallel  Distributed  Clustered  Handheld ANSWERS: a. Batch processing:-   Jobs with similar needs are batched together and run through the computer as a group by an operator or automatic job sequencer. Performance is increased by attempting to keep CPU and I/O devices busy at all times through buffering, off-line operation, spooling, and multi-programming. Batch is good for executing large jobs that need little interaction; it can be submitted and picked up later. b. Interactive System:-   This system is composed of many short transactions where the results of the next transaction may be unpredictable. Response time needs to be short (seconds) since the user submits and waits for the result. c. Time sharing:-   This systems uses CPU scheduling and multipro-gramming to provide econ...

What is a Fair lock in multithreading?

  Photo by  João Jesus  from  Pexels In Java, there is a class ReentrantLock that is used for implementing Fair lock. This class accepts optional parameter fairness.  When fairness is set to true, the RenentrantLock will give access to the longest waiting thread.  The most popular use of Fair lock is in avoiding thread starvation.  Since longest waiting threads are always given priority in case of contention, no thread can starve.  The downside of Fair lock is the low throughput of the program.  Since low priority or slow threads are getting locks multiple times, it leads to slower execution of a program. The only exception to a Fair lock is tryLock() method of ReentrantLock.  This method does not honor the value of the fairness parameter.

What is the MES system? 12 Important Questions Answered

 What is MES system? MES is the execution layer between the planning layer and the on-site automation system. It is mainly responsible for workshop production management and scheduling execution. A well-designed MES system can integrate management functions such as production scheduling, product tracking, quality control, equipment failure analysis, network reporting, etc. on a unified platform. Using a unified database and connecting through the network can be used for the production department, quality inspection department, Process department, logistics department, etc. provide workshop management information services. The system helps companies implement complete closed-loop production by emphasizing the overall optimization of the manufacturing process, and assists companies in establishing an integrated and real-time ERP/MES/SFC information system. The main functions of the MES system: It provides flexible and powerful tools for enterprise production managers to monitor and m...