需求
- FTP工具
与远程网络服务器交互文件
思路
引入相关依赖调用API,自己造车轮……没那个必要
实现
需要引入依赖:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.9.0</version>
</dependency>
代码:
public class SimpleFTPClient extends JFrame {
private JTextField hostField;
private JTextField userField;
private JPasswordField passField;
private JTextField fileField;
private FTPClient ftpClient;
public SimpleFTPClient() {
setTitle("Simple FTP Client");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 2));
// Create GUI components
JLabel hostLabel = new JLabel("FTP Host:");
hostField = new JTextField();
JLabel userLabel = new JLabel("Username:");
userField = new JTextField();
JLabel passLabel = new JLabel("Password:");
passField = new JPasswordField();
JLabel fileLabel = new JLabel("File Path:");
fileField = new JTextField();
JButton uploadButton = new JButton("Upload");
uploadButton.addActionListener(new UploadAction());
JButton downloadButton = new JButton("Download");
downloadButton.addActionListener(new DownloadAction());
// Add components to the frame
add(hostLabel);
add(hostField);
add(userLabel);
add(userField);
add(passLabel);
add(passField);
add(fileLabel);
add(fileField);
add(uploadButton);
add(downloadButton);
ftpClient = new FTPClient();
}
private class UploadAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String host = hostField.getText();
String user = userField.getText();
String pwd = new String(passField.getPassword());
String path = fileField.getText();
try {
ftpClient.connect(host);
ftpClient.login(user, pwd);
ftpClient.enterLocalActiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
FileInputStream inputStream = new FileInputStream(path);
boolean storeFileSuccess = ftpClient.storeFile(path, inputStream);
inputStream.close();
if (storeFileSuccess) {
JOptionPane.showMessageDialog(SimpleFTPClient.this, "upload file success");
} else {
JOptionPane.showMessageDialog(SimpleFTPClient.this, "upload file failed");
}
} catch (IOException ioException) {
System.out.println(ioException.getMessage());
JOptionPane.showMessageDialog(SimpleFTPClient.this, "upload file error");
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
}
private class DownloadAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String host = hostField.getText();
String user = userField.getText();
String pwd = new String(passField.getPassword());
String path = fileField.getText();
try {
ftpClient.connect(host);
ftpClient.login(user, pwd);
ftpClient.enterLocalActiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
FileOutputStream outputStream = new FileOutputStream("downloaded_" + path);
boolean retrieveFileSuccess = ftpClient.retrieveFile(path, outputStream);
outputStream.close();
if (retrieveFileSuccess) {
JOptionPane.showMessageDialog(SimpleFTPClient.this, "download file success");
} else {
JOptionPane.showMessageDialog(SimpleFTPClient.this, "download file failed");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(SimpleFTPClient.this, "download file error");
System.out.println(ex.getMessage());
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ioException) {
System.out.println(ioException.getMessage());
}
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new SimpleFTPClient().setVisible(true));
}
}
需求
- 原子钟校时
从网上同步原子钟时间。全世界有很多原子钟,可以把它们都列出来
思路
访问原子钟网址,获取偏移量,调整时间
实现
public class NTPTimeSync {
public static void main(String[] args) {
String[] ntpServers = {"pool.ntp.org",
"time.google.com",
"time.windows.com",
"time.apple.com",
"time.nist.gov"};
for (String server : ntpServers){
try{
System.out.println("Querying NTP Server: " + server);
//NTP客户端 超时时间1秒 打开连接
NTPUDPClient client = new NTPUDPClient();
client.setDefaultTimeout(1000);
client.open();
//从服务器获取时间
InetAddress address = InetAddress.getByName(server);
TimeInfo info = client.getTime(address);
info.computeDetails();
//计算本地时间与NTP时间的偏移量,并根据偏移量调整本地时间,以得到同步后的原子时间。
Long offset = info.getOffset();
Long currentTimeMillis = System.currentTimeMillis();
LocalDateTime atomicTime = LocalDateTime.ofInstant(
Instant.ofEpochMilli(currentTimeMillis + offset),
ZoneId.systemDefault());
System.out.println("Atomic time from " + server + ":" + atomicTime);
client.close();
break;
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
}
需求
- 获取当前天气
获取某个地区当前的天气情况
思路
访问API
实现
public class WeatherFetcher {
private static final String API_KEY = "";
private static final String API = "http://api.openweathermap.org/data/2.5/weather";
public static void main(String[] args) {
String location = "Beijing";
String requestUrl = API + "?q=" + location + "&appid=" + API_KEY + "&units=metric";
try {
String response = ApiUtils.getApiResponse(requestUrl,"GET");
JSONObject jsonObject = new JSONObject(response);
JSONObject main = jsonObject.getJSONObject("main");
Double temperature = (Double) main.get("temp");
Integer humidity = (Integer) main.get("humidity");
JSONObject weather = (JSONObject) jsonObject.getJSONArray("weather").get(0);
String description = weather.getString("description");
System.out.println("Current weather in " + location + ":");
System.out.println("Temperature: " + temperature + "°C");
System.out.println("Humidity: " + humidity + "%");
System.out.println("Description: " + description);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}