⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ftpclass.java

📁 ftp上传下载,支持续传,使用swing组件
💻 JAVA
字号:
package com.hujing;

import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

public class FtpClass {

	private JTextField textField;

	private JTextArea textArea;

	private JTextField ftpPort;

	private JTextField remotePath;

	private JTextField fileName;

	private JPasswordField ftpPwd;

	private JTextField ftpUser;

	private JTextField ftpUrl;

	private JFrame frame;

	private FtpClient ftpClient;

	private JFileChooser fileChooser;

	private JLabel statesText;

	private JButton connBtn = new JButton();

	private JLabel total = new JLabel();

	static String last_unUploadFile = "";

	/**
	 * Launch the application
	 * 
	 * @param args
	 */
	public static void main(String args[]) {
		try {
			JFrame.setDefaultLookAndFeelDecorated(true);
			FtpClass window = new FtpClass();
			window.frame.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the application
	 */
	public FtpClass() {
		initialize();
		getAllFiles();
		UploadThread uploadThread = new UploadThread();
		new Thread(uploadThread).start();
		textArea.append("已连接到FTP服务器\n");
	}

	/**
	 * Initialize the contents of the frame
	 */
	@SuppressWarnings("deprecation")
	private void initialize() {
		frame = new JFrame();
		// 关闭应用程序
		frame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				if (ftpClient != null) {
					try {
						ftpClient.closeServer();
						System.exit(0);
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}
		});

		frame.setResizable(false);
		frame.setTitle("FTP");
		frame.getContentPane().setLayout(null);
		frame.setBounds(100, 100, 482, 393);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		final JLabel ftpLabel = new JLabel();
		ftpLabel.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		ftpLabel.setText("服务url:");
		ftpLabel.setBounds(21, 23, 60, 15);
		frame.getContentPane().add(ftpLabel);

		ftpUrl = new JTextField();
		ftpUrl.setText("192.168.1.87");
		ftpUrl.setBounds(87, 21, 262, 20);
		frame.getContentPane().add(ftpUrl);

		final JLabel label = new JLabel();
		label.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		label.setText("用户名:");
		label.setBounds(21, 49, 60, 15);
		frame.getContentPane().add(label);

		ftpUser = new JTextField();
		ftpUser.setText("efly");
		ftpUser.setBounds(87, 47, 299, 20);
		frame.getContentPane().add(ftpUser);

		final JLabel label_1 = new JLabel();
		label_1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		label_1.setText("密码:");
		label_1.setBounds(21, 75, 60, 15);
		frame.getContentPane().add(label_1);

		ftpPwd = new JPasswordField();
		ftpPwd.setText("efly");
		ftpPwd.setBounds(87, 73, 299, 20);
		frame.getContentPane().add(ftpPwd);

		// 连接到FTP服务器事件
		connBtn.addActionListener(new ActionListener() {

			@SuppressWarnings("deprecation")
			public void actionPerformed(ActionEvent e) {
				String ip = ftpUrl.getText();
				int port = Integer.parseInt(ftpPort.getText());
				String user = ftpUser.getText();
				String pwd = ftpPwd.getText();
				String path = remotePath.getText();
				connectToFTP(ip, port, user, pwd, path);
			}
		});
		connBtn.setText("连接");
		connBtn.setBounds(392, 45, 61, 23);
		frame.getContentPane().add(connBtn);

		fileName = new JTextField();
		fileName.setText("e:/img/");
		fileName.setBounds(21, 116, 432, 20);
		frame.getContentPane().add(fileName);
		// 打开文件选择对话框

		final JButton uploadBtn = new JButton();

		// 上传文件事件监听
		uploadBtn.addActionListener(new ActionListener() {
			// 执行上传
			public void actionPerformed(ActionEvent e) {
				uploadFileToFTP();
			}
		});
		uploadBtn.setText("上传");
		uploadBtn.setBounds(382, 158, 71, 23);
		frame.getContentPane().add(uploadBtn);

		remotePath = new JTextField();
		// remotePath.setFont(new Font("", Font.BOLD, 12));
		remotePath.setEditable(false);
		remotePath.setText("/ourfiles/test/");
		remotePath.setBounds(21, 159, 355, 20);
		frame.getContentPane().add(remotePath);

		final JLabel label_2 = new JLabel();
		label_2.setText("远程FTP目录");
		label_2.setBounds(21, 143, 80, 15);
		frame.getContentPane().add(label_2);

		final JButton button = new JButton();

		// 断开FTP
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				disconnect();
			}
		});
		button.setText("断开");
		button.setBounds(392, 71, 61, 23);
		frame.getContentPane().add(button);

		statesText = new JLabel();
		statesText.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		statesText.setBounds(366, 321, 65, 18);
		frame.getContentPane().add(statesText);

		ftpPort = new JTextField();
		ftpPort.setText("21");
		ftpPort.setBounds(417, 21, 36, 20);
		frame.getContentPane().add(ftpPort);

		final JLabel label_3 = new JLabel();
		label_3.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		label_3.setText("端口:");
		label_3.setBounds(367, 21, 44, 18);
		frame.getContentPane().add(label_3);

		final JButton button_2 = new JButton();
		button_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				getAllFiles();
			}
		});

		textArea = new JTextArea();
		textArea.setEditable(false);
		// textArea.setFont(new Font("", Font.BOLD, 12));
		textArea.setBounds(21, 195, 87, 19);
		frame.getContentPane().add(textArea);

		final JScrollPane scrollPane = new JScrollPane();
		scrollPane.setAutoscrolls(true);
		scrollPane.setViewportView(textArea);
		scrollPane.setBounds(21, 194, 432, 121);
		frame.getContentPane().add(scrollPane);

		total.setBounds(21, 323, 134, 15);
		frame.getContentPane().add(total);

		final JLabel label_4 = new JLabel();
		label_4.setText("本地上传目录");
		label_4.setBounds(21, 100, 80, 15);
		frame.getContentPane().add(label_4);

		textField = new JTextField();
		textField.setEditable(false);
		textField.setBounds(433, 322, 18, 15);
		frame.getContentPane().add(textField);

		fileChooser = new JFileChooser();
		fileChooser.setBounds(21, 91, 450, 300);

	}

	// 连接到FTP服务器
	private boolean connectToFTP(String ip, int port, String username,
			String pwd, String path) {

		ftpClient = new FtpClient();

		try {
			ftpClient.openServer(ip, port);
			ftpClient.login(username, pwd);
			if (path.length() != 0) {
				ftpClient.cd(path);
				ftpClient.binary();
			}
			statesText.setText("在线");
			statesText.setForeground(Color.BLUE);
			textField.setBackground(new Color(0, 128, 0));
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			statesText.setText("连接失败");
			statesText.setForeground(Color.RED);
			textField.setBackground(new Color(128, 0, 0));
			return false;
		}
	}

	// 断开连接
	private void disconnect() {
		try {
			if (ftpClient != null) {
				ftpClient.closeServer(); // 关闭连接
				statesText.setText("离线");
				statesText.setForeground(Color.DARK_GRAY);
				textField.setBackground(new Color(76, 76, 76));
			}
		} catch (IOException e) {
			e.printStackTrace();
			statesText.setText("断开失败");
			statesText.setForeground(Color.RED);
		}
	}

	// 上传文件到远程FTP
	public void uploadFileToFTP() {

		String localFileDir = ""; // 本地文件目录
		String remoteDir = ""; // 远程FTP文件目录

		localFileDir = fileName.getText(); // 得到本地上传路径
		remoteDir = remotePath.getText(); // 得到远程上传路径

		DateFormat transTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化时间
		String upLoadTime = transTime.format(new Date());

		TelnetOutputStream telnetOS;

		File localFilesList = new File(localFileDir);
		String[] allLocalFiles = localFilesList.list();// 得到本地目录的所有文件
		String[] filesNameList = new String[allLocalFiles.length];// 得到本地目录所有文件的文件名

		// 遍历本地文件, 将文件一一上传
		for (int i = 0; i < allLocalFiles.length; i++) {

			File tempFilesList = new File(localFileDir + allLocalFiles[i]);

			if (tempFilesList.isFile()) {
				filesNameList[i] = tempFilesList.getName();
				try {
					telnetOS = ftpClient.put(remoteDir + filesNameList[i]);
					FileInputStream fileInput = new FileInputStream(
							localFileDir + filesNameList[i]);
					last_unUploadFile = filesNameList[i];
					byte[] bytes = new byte[1024]; // 每次读 1024 byte
					int flag = 0;

					while ((flag = fileInput.read(bytes)) != -1) {
						telnetOS.write(bytes, 0, flag);
					}
					textArea.append("状态:文件 " + filesNameList[i] + " 于 "
							+ upLoadTime + " 上传完毕 \n");

					last_unUploadFile = "";
					System.out.println("最后上传文件:" + last_unUploadFile);
					fileInput.close();
					telnetOS.close();
					tempFilesList.delete();
				} catch (IOException e) {
					// e.printStackTrace();
					textArea.append("状态:文件 " + filesNameList[i] + " 重新上传\n");
				}
			}
		}
	}

	// 得到本地所有文件及名字
	@SuppressWarnings("unchecked")
	private List getAllFiles() {

		File dirFile = new File("E:\\img");// 本地文件目录

		String[] localFilesList = dirFile.list(); // 得到本地文件
		String[] str = new String[localFilesList.length];

		total.setText("本地目录文件数:" + localFilesList.length + " 个");
		List<String> localList = new ArrayList<String>();

		for (int i = 0; i < localFilesList.length; i++) {
			File temFile = new File("E:\\img\\" + localFilesList[i]);
			if (temFile.isFile()) {
				str[i] = temFile.getName();
				localList.add(temFile.getName());
			}
		}
		return localList;
	}

	// 得到远程FTP服务器指定目录文件列表
	 @SuppressWarnings({ "unchecked", "unused" })
	private List getRemoteFilesList() {
	 List<String> remoteFiles = new ArrayList<String>();
	 try {
	 BufferedReader bufferedReader = new BufferedReader(
	 new InputStreamReader(ftpClient.nameList(remotePath
	 .getText())));
	 String str = "";
	 while ((str = bufferedReader.readLine()) != null) {
	 remoteFiles.add(str);
	 }
	 bufferedReader.close();
	 } catch (IOException e) {
	 e.printStackTrace();
	 }
	 return remoteFiles;
	 }

	// 连接和上传的控制线程
	class UploadThread implements Runnable {

		boolean connFlag = false; // 连接标志

		@SuppressWarnings("deprecation")
		public void run() {
			while (true) {
				String ip = ftpUrl.getText();
				int port = Integer.parseInt(ftpPort.getText());
				String user = ftpUser.getText();
				String pwd = ftpPwd.getText();
				String path = remotePath.getText();

				connFlag = connectToFTP(ip, port, user, pwd, path); // 判断是否在线

				if (connFlag) {
					try {
						Thread.sleep(30000);
						uploadFileToFTP(); // 上传
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				} else {
					try {
						Thread.sleep(30000);
						connectToFTP(ip, port, user, pwd, path); // 断开重连
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -