java swing 显示ip地址输入框 端口号输入框实现文件传输
时间: 2023-09-14 19:07:43 浏览: 153
SWING做一个IP输入框
4星 · 用户满意度95%
以下是一个简单的Java Swing程序,用于实现文件传输的IP地址输入框和端口号输入框:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class FileTransfer extends JFrame implements ActionListener {
private JTextField ipField;
private JTextField portField;
private JButton sendButton;
private JButton chooseButton;
private JFileChooser fileChooser;
public FileTransfer() {
setTitle("File Transfer");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel topPanel = new JPanel();
topPanel.setLayout(new GridLayout(2, 2));
JLabel ipLabel = new JLabel("IP Address:");
ipField = new JTextField();
JLabel portLabel = new JLabel("Port:");
portField = new JTextField();
topPanel.add(ipLabel);
topPanel.add(ipField);
topPanel.add(portLabel);
topPanel.add(portField);
add(topPanel, BorderLayout.NORTH);
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(1, 2));
chooseButton = new JButton("Choose File...");
chooseButton.addActionListener(this);
centerPanel.add(chooseButton);
sendButton = new JButton("Send File");
sendButton.addActionListener(this);
centerPanel.add(sendButton);
add(centerPanel, BorderLayout.CENTER);
fileChooser = new JFileChooser();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == chooseButton) {
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
// Do something with the file
}
} else if (e.getSource() == sendButton) {
String ipAddress = ipField.getText();
int portNumber = Integer.parseInt(portField.getText());
File file = fileChooser.getSelectedFile();
try {
Socket socket = new Socket(ipAddress, portNumber);
OutputStream outputStream = socket.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
fileInputStream.close();
outputStream.close();
socket.close();
JOptionPane.showMessageDialog(this, "File sent successfully!");
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "Error sending file: " + ex.getMessage());
}
}
}
public static void main(String[] args) {
new FileTransfer();
}
}
```
这个程序创建了一个窗口,包含一个IP地址输入框、一个端口号输入框、一个“Choose File...”按钮和一个“Send File”按钮。当用户点击“Choose File...”按钮时,程序打开一个文件选择器,允许用户选择要发送的文件。当用户点击“Send File”按钮时,程序使用Socket连接到指定的IP地址和端口号,并将文件发送到远程主机。
请注意,此程序仅是一个示例,并不包含完整的错误处理和安全功能。在实际应用中,您需要添加更多的错误处理和安全检查,以确保文件传输的安全和可靠。
阅读全文