Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.apache.commons.net.PrintCommandListener;
- import org.apache.commons.net.ftp.*;
- import javax.swing.*;
- import javax.swing.table.AbstractTableModel;
- import javax.swing.text.DefaultCaret;
- import java.awt.*;
- import java.awt.event.*;
- import java.io.*;
- import java.nio.ByteBuffer;
- import java.nio.CharBuffer;
- import java.nio.charset.Charset;
- import java.nio.charset.CharsetDecoder;
- class MyTableModel extends AbstractTableModel {
- private String[] columnNames = {"Name",
- "Size",
- "Last modified"};
- private Object[][] data = {};
- MyTableModel() {
- }
- MyTableModel(Object[][] data) {
- this.data = data;
- }
- public int getColumnCount() {
- return columnNames.length;
- }
- public int getRowCount() {
- return data.length;
- }
- public String getColumnName(int col) {
- return columnNames[col];
- }
- public Object getValueAt(int row, int col) {
- return data[row][col];
- }
- public Class getColumnClass(int c) {
- return getValueAt(0, c).getClass();
- }
- public boolean isCellEditable(int row, int col) {
- return false;
- }
- }
- public class FTPClient {
- private String FTPADDR = "localhost";
- private String username = "demo";
- private String password = "";
- private String localPath = "C://ftptest";
- private JTextArea logArea = null;
- private JTable table = null;
- private boolean connected = false;
- private boolean downloading = false;
- private final int NAME = 0;
- private final int SIZE = 1;
- private final int LASTMODIFIED = 2;
- private final int COUNT = 3;
- private static class TextAreaOutputStream extends OutputStream {
- private JTextArea textArea;
- private CharsetDecoder decoder;
- TextAreaOutputStream(JTextArea textArea) {
- this.textArea = textArea;
- this.decoder = Charset.defaultCharset().newDecoder();
- }
- @Override
- public void write(byte b[]) throws IOException {
- write(b, 0, b.length);
- }
- @Override
- public void write(byte b[], int off, int len) throws IOException {
- CharBuffer charBuffer = decoder.decode(ByteBuffer.wrap(b, off, len));
- textArea.append(charBuffer.toString());
- }
- public void write(int b) throws IOException {
- CharBuffer charBuffer = decoder.decode(ByteBuffer.wrap(new byte[]{(byte) b}));
- textArea.append(charBuffer.toString());
- }
- }
- private org.apache.commons.net.ftp.FTPClient ftp = null;
- public static void main(String[] args) {
- new FTPClient();
- }
- private FTPClient() {
- EventQueue.invokeLater(() -> {
- try {
- UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
- } catch (Exception ex) {
- System.out.println("Exception caught:");
- System.out.println(ex.toString());
- ex.printStackTrace();
- }
- JFrame frame = new JFrame("FTP Client 1.0");
- frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
- frame.setLayout(new BorderLayout());
- frame.add(new LayoutPane());
- frame.pack();
- frame.setResizable(false);
- frame.setLocationRelativeTo(null);
- frame.setVisible(true);
- ftp = new org.apache.commons.net.ftp.FTPClient();
- ftp.setAutodetectUTF8(true);
- ftp.setControlEncoding("UTF-8");
- ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
- });
- }
- private class LayoutPane extends JPanel {
- private LayoutPane() {
- JButton button = new JButton("Connect");
- button.setPreferredSize(new Dimension(90, 22));
- JButton dlButton = new JButton("Download");
- dlButton.setPreferredSize(new Dimension(90, 22));
- dlButton.setEnabled(false);
- JLabel addressLabel = new JLabel("FTP Server:");
- JLabel sizeLabel = new JLabel("Size of downloading files will be smaller than");
- JLabel usernameLabel = new JLabel("Username:");
- JLabel passwordLabel = new JLabel("Password:");
- JLabel localPathLabel = new JLabel("Local path:");
- JTextField addressField = new JTextField("localhost", 20);
- JTextField sizeField = new JTextField("1000", 6);
- JTextField usernameField = new JTextField(username, 9);
- JTextField passwordField = new JTextField(password, 9);
- JTextField localPathField = new JTextField(localPath, 20);
- setLayout(new GridBagLayout());
- JPanel paneTop = new JPanel(new GridBagLayout());
- JPanel paneMid = new JPanel(new GridBagLayout());
- JPanel paneBottomMid = new JPanel(new GridBagLayout());
- JPanel paneBot = new JPanel(new GridBagLayout());
- GridBagConstraints gbc = new GridBagConstraints();
- gbc.gridx = 0;
- gbc.gridy = 0;
- gbc.insets = new Insets(2, 2, 2, 2);
- gbc.fill = GridBagConstraints.HORIZONTAL;
- gbc.anchor = GridBagConstraints.WEST;
- paneTop.add(addressLabel, gbc);
- gbc.gridx++;
- paneTop.add(addressField, gbc);
- gbc.gridx++;
- paneTop.add(usernameLabel, gbc);
- gbc.gridx++;
- paneTop.add(usernameField, gbc);
- gbc.gridx++;
- paneTop.add(passwordLabel, gbc);
- gbc.gridx++;
- paneTop.add(passwordField, gbc);
- gbc.gridx++;
- gbc.anchor = GridBagConstraints.EAST;
- paneTop.add(button, gbc);
- gbc.gridx = 0;
- gbc.gridy = 0;
- gbc.anchor = GridBagConstraints.NORTH;
- add(paneTop, gbc);
- gbc.gridx = 0;
- gbc.gridy = 0;
- table = new JTable(new MyTableModel());
- gbc.fill = GridBagConstraints.BOTH;
- JScrollPane scrollTable = new JScrollPane(table);
- scrollTable.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
- gbc.weightx = 1;
- gbc.weighty = 1;
- paneMid.add(scrollTable, gbc);
- gbc.weightx = 0;
- gbc.weighty = 0;
- gbc.gridy++;
- gbc.fill = GridBagConstraints.HORIZONTAL;
- gbc.gridy = 2;
- add(paneMid, gbc);
- gbc.gridx = 0;
- gbc.gridy = 0;
- gbc.anchor = GridBagConstraints.SOUTH;
- paneBottomMid.add(localPathLabel, gbc);
- gbc.gridx++;
- paneBottomMid.add(localPathField, gbc);
- gbc.gridx++;
- paneBottomMid.add(sizeLabel, gbc);
- gbc.gridx++;
- paneBottomMid.add(sizeField, gbc);
- gbc.gridx++;
- paneBottomMid.add(dlButton, gbc);
- gbc.gridx = 0;
- gbc.gridy = 3;
- add(paneBottomMid, gbc);
- gbc.gridx = 0;
- gbc.gridy = 0;
- gbc.fill = GridBagConstraints.BOTH;
- logArea = new JTextArea(8, 40);
- logArea.setFont(new Font("Consolas", Font.PLAIN, 12));
- logArea.setEditable(false);
- PrintStream ps = new PrintStream(new BufferedOutputStream((new TextAreaOutputStream(logArea))));
- System.setOut(ps);
- JScrollPane scrollLog = new JScrollPane(logArea);
- DefaultCaret caret = (DefaultCaret) logArea.getCaret();
- caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
- scrollLog.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
- gbc.weightx = 1;
- gbc.weighty = 1;
- paneBot.add(scrollLog, gbc);
- gbc.gridy = 4;
- add(paneBot, gbc);
- gbc.fill = GridBagConstraints.BOTH;
- gbc.gridx = 0;
- gbc.gridy = 0;
- gbc.weightx = 0;
- gbc.weighty = 0;
- System.out.println("HEY");
- button.addActionListener(e -> {
- if (!connected) {
- connected = true;
- FTPADDR = addressField.getText();
- username = usernameField.getText();
- password = passwordField.getText();
- addressField.setEditable(false);
- usernameField.setEditable(false);
- passwordField.setEditable(false);
- button.setText("Disconnect");
- dlButton.setEnabled(true);
- new Thread(() -> {
- try {
- logArea.setText("");
- ftp.connect(FTPADDR);
- ftp.setFileType(FTP.BINARY_FILE_TYPE);
- ftp.enterLocalPassiveMode();
- ftp.login(username, password);
- int reply = ftp.getReplyCode();
- if (!FTPReply.isPositiveCompletion(reply)) {
- throw new Exception("Can't connect exception");
- }
- FTPFile[] list = ftp.listFiles();
- getFileTable(list);
- } catch (Exception e1) {
- disconnect();
- e1.printStackTrace();
- System.out.println("Exception caught:");
- System.out.println(e1.toString());
- connected = false;
- button.setText("Connect");
- dlButton.setEnabled(false);
- addressField.setEditable(true);
- usernameField.setEditable(true);
- passwordField.setEditable(true);
- }
- }).start();
- } else {
- connected = false;
- new Thread(FTPClient.this::disconnect).start();
- button.setText("Connect");
- dlButton.setEnabled(false);
- addressField.setEditable(true);
- usernameField.setEditable(true);
- passwordField.setEditable(true);
- }
- });
- dlButton.addActionListener(e -> new Thread(() -> {
- if (!downloading) {
- sizeField.setEnabled(false);
- localPathField.setEnabled(false);
- downloading = true;
- try {
- localPath = localPathField.getText();
- downloadFiles(".", Integer.parseInt(sizeField.getText()));
- downloading = false;
- } catch (Exception e1) {
- System.out.println("Exception caught:");
- System.out.println(e1.toString());
- }
- sizeField.setEnabled(true);
- localPathField.setEnabled(true);
- } else {
- downloading = false;
- sizeField.setEnabled(true);
- localPathField.setEnabled(true);
- }
- }).start());
- table.addKeyListener(new KeyAdapter() {
- @Override
- public void keyPressed(KeyEvent e) {
- int row = table.getSelectedRow();
- if (e.getKeyCode() == KeyEvent.VK_ENTER && (table.getValueAt(row, SIZE) instanceof String)) {
- getFileTable(changeDir(table.getValueAt(table.getSelectedRow(), NAME).toString()));
- }
- }
- });
- table.addMouseListener(new MouseAdapter() {
- public void mousePressed(MouseEvent me) {
- JTable table = (JTable) me.getSource();
- Point p = me.getPoint();
- int row = table.rowAtPoint(p);
- if (me.getClickCount() == 2 && row != -1 && (table.getValueAt(row, SIZE) instanceof String)) {
- getFileTable(changeDir(table.getValueAt(row, NAME).toString()));
- }
- }
- });
- }
- }
- private FTPFile[] changeDir(String pathname) {
- FTPFile[] files;
- try {
- if (!ftp.changeWorkingDirectory(pathname)) {
- throw new IOException("Can't change directory exception");
- }
- files = ftp.listFiles();
- } catch (IOException e) {
- System.out.println("Exception caught:");
- System.out.println(e.toString());
- files = null;
- }
- return files;
- }
- private void downloadFiles(String remotePath, int limit) {
- try {
- String workDir = ftp.printWorkingDirectory();
- FTPFile[] list = ftp.listFiles(remotePath);
- for (FTPFile aList : list) {
- String name = aList.getName();
- if (aList.isDirectory() && !name.equals(".") && !name.equals("..")) {
- downloadFiles(remotePath + "/" + name, limit);
- } else if (aList.getSize() <= limit) {
- File path = new File(localPath + workDir + remotePath);
- path.mkdirs();
- FileOutputStream fos = new FileOutputStream(localPath + workDir + remotePath + "/" + name);
- if (downloading) {
- ftp.retrieveFile(remotePath + "/" + name, fos);
- } else throw new IOException("Downloading aborted by user");
- fos.close();
- }
- }
- } catch (IOException e) {
- System.out.println("Exception caught:");
- System.out.println(e.toString());
- }
- }
- private void disconnect() {
- try {
- ftp.logout();
- ftp.disconnect();
- table.setModel(new MyTableModel());
- } catch (IOException e) {
- System.out.println("Exception caught:");
- System.out.println(e.toString());
- }
- }
- private Object[][] getFileTable(FTPFile[] file) {
- Object[][] data = new Object[file.length + 1][COUNT];
- data[0][NAME] = "..";
- data[0][SIZE] = "DIR";
- data[0][LASTMODIFIED] = "";
- for (int i = 1; i < file.length + 1; i++) {
- data[i][NAME] = file[i - 1].getName();
- data[i][SIZE] = (file[i - 1].isDirectory() ? "DIR" : file[i - 1].getSize());
- data[i][LASTMODIFIED] = file[i - 1].getTimestamp().getTime().toString();
- }
- table.setModel(new MyTableModel(data));
- table.revalidate();
- return data;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement