示範在 Applet 中使用 sun.net.ftp.FtpClient 實作 FTP 連線、登入、列出檔案、上傳檔案功能。介面包含主機、帳號、密碼輸入欄、連線/斷開按鈕、檔案列表顯示區。注意:sun.* 套件為內部 API,不保證跨 JDK 版本相容,生產環境建議改用 Apache Commons Net 等標準庫。
import sun.net.ftp.*;
import sun.net.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.io.*;
public class FtpApplet extends Applet {
FtpClient ftp;
DataOutputStream outputs;
TelnetInputStream ins;
TelnetOutputStream outs;
TextArea lsArea;
Label lblPrompt;
Button btnConn, btnClose;
TextField txtHost, txtUser, txtPass;
String hostname = "";
String msg = "未連線";
public void init() {
setBackground(Color.white);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
lblPrompt = new Label(msg);
btnConn = new Button("連接");
btnClose = new Button("斷開"); btnClose.setEnabled(false);
txtHost = new TextField(20);
txtUser = new TextField(15);
txtPass = new TextField(15); txtPass.setEchoChar('*');
lsArea = new TextArea(30, 80); lsArea.setEditable(false);
// 佈局程式碼省略,請參考原始碼
}
public boolean connect(String host, String user, String pass) {
this.hostname = host;
lblPrompt.setText("連線中...");
try {
ftp = new FtpClient(host);
ftp.login(user, pass);
ftp.binary();
showFileContents();
lblPrompt.setText("連線成功:" + host);
return true;
} catch (FtpLoginException e) { msg = "登入失敗:" + host; }
catch (IOException e) { msg = "連線失敗:" + host; }
catch (SecurityException e) { msg = "安全限制:" + host; }
lblPrompt.setText(msg);
return false;
}
public void stop() {
try { if (ftp != null) ftp.closeServer(); } catch (IOException ignored) {}
}
public boolean action(Event evt, Object obj) {
if (evt.target == btnConn) {
if (connect(txtHost.getText(), txtUser.getText(), txtPass.getText())) {
btnConn.setEnabled(false); btnClose.setEnabled(true);
}
return true;
}
if (evt.target == btnClose) {
stop();
btnConn.setEnabled(true); btnClose.setEnabled(false);
lblPrompt.setText("已斷開:" + hostname);
return true;
}
return super.action(evt, obj);
}
public boolean sendFile(String path) {
if (ftp == null) return false;
lblPrompt.setText("上傳中...");
try {
String fileName = path.substring(path.lastIndexOf("\\") + 1);
RandomAccessFile raf = new RandomAccessFile(path, "r");
outs = ftp.put(fileName);
outputs = new DataOutputStream(outs);
int ch;
while ((ch = raf.read()) != -1) outputs.write(ch);
outs.close(); raf.close();
lblPrompt.setText("上傳成功");
showFileContents();
return true;
} catch (IOException e) {
lblPrompt.setText("上傳失敗");
return false;
}
}
void showFileContents() {
try {
ins = ftp.list();
StringBuilder sb = new StringBuilder();
int ch;
while ((ch = ins.read()) >= 0) sb.append((char)ch);
lsArea.setText(sb.toString());
ins.close();
} catch (IOException ignored) {}
}
public static void main(String[] args) {
Frame f = new Frame("FTP Client");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
FtpApplet applet = new FtpApplet();
applet.init(); applet.start();
f.add(applet); f.pack(); f.setVisible(true);
}
}
安全性提醒: