If you're working with JSch for SFTP file operations in Java and need to retrieve today's date—whether for logging, naming files, or timestamping data—here’s how to do it:
✅ Code Example:
java
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
public class SFTPExample {
public static void main(String[] args) {
String host = "sftp.example.com";
String user = "username";
String password = "password";
int port = 22;
Session session = null;
ChannelSftp channelSftp = null;
try {
// Initialize JSch
JSch jsch = new JSch();
session = jsch.getSession(user, host, port);
session.setPassword(password);
// Configure session properties
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
// Connect to the server
session.connect();
// Open SFTP channel
channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
// Get today's date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String todayDate = dateFormat.format(new Date());
System.out.println("Today's Date: " + todayDate);
// ➕ SFTP operations can go here (e.g., upload/download files)
} catch (Exception e) {
e.printStackTrace();
} finally {
if (channelSftp != null && channelSftp.isConnected()) {
channelSftp.disconnect();
}
if (session != null && session.isConnected()) {
session.disconnect();
}
}
}
}
📘 Explanation:
- JSch Setup:
- The code establishes a secure SFTP connection using the JSch library.
- Date Handling:
-
SimpleDateFormat
is used to get the current date in yyyy-MM-dd
format, which is great for naming files or folders in a consistent way. - Flexible Integration:
- You can plug
todayDate
into file paths or names, like:
java
String remoteFilePath = "/uploads/report_" + todayDate + ".csv";
- Where to Use:
- Add SFTP operations (e.g.,
channelSftp.put(...)
or channelSftp.get(...)
) right after retrieving the date.
🧩 Use Cases:
- Timestamp file uploads or downloads
- Organize logs by date
- Sync daily backups or reports