Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class FTPUtil {
- public static void uploadDirectory(FTPClient ftpClient,
- String remoteDirPath, String localParentDir, String remoteParentDir)
- throws IOException {
- System.out.println("LISTING directory: " + localParentDir);
- File localDir = new File(localParentDir);
- File[] subFiles = localDir.listFiles();
- if (subFiles != null && subFiles.length > 0) {
- for (File item : subFiles) {
- String remoteFilePath = remoteDirPath + "/" + remoteParentDir
- + "/" + item.getName();
- if (remoteParentDir.equals("")) {
- remoteFilePath = remoteDirPath + "/" + item.getName();
- }
- if (item.isFile()) {
- // upload the file
- String localFilePath = item.getAbsolutePath();
- System.out.println("About to upload the file: " + localFilePath);
- boolean uploaded = uploadSingleFile(ftpClient,
- localFilePath, remoteFilePath);
- if (uploaded) {
- System.out.println("UPLOADED a file to: "
- + remoteFilePath);
- } else {
- System.out.println("COULD NOT upload the file: "
- + localFilePath);
- }
- } else {
- // create directory on the server
- boolean created = ftpClient.makeDirectory(remoteFilePath);
- if (created) {
- System.out.println("CREATED the directory: "
- + remoteFilePath);
- } else {
- System.out.println("COULD NOT create the directory: "
- + remoteFilePath);
- }
- // upload the sub directory
- String parent = remoteParentDir + "/" + item.getName();
- if (remoteParentDir.equals("")) {
- parent = item.getName();
- }
- localParentDir = item.getAbsolutePath();
- uploadDirectory(ftpClient, remoteDirPath, localParentDir,
- parent);
- }
- }
- }
- }
- public static boolean uploadSingleFile(FTPClient ftpClient,
- String localFilePath, String remoteFilePath) throws IOException {
- File localFile = new File(localFilePath);
- InputStream inputStream = new FileInputStream(localFile);
- try {
- ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
- return ftpClient.storeFile(remoteFilePath, inputStream);
- } finally {
- inputStream.close();
- }
- }
- public class MainApp {
- public static void main(String[] args) {
- String server = "127.0.0.1";
- int port = 14147;
- String user = "user";
- String pass = "pass";
- FTPClient ftpClient = new FTPClient();
- try {
- // connect and login to the server
- ftpClient.connect(server, port);
- // use local passive mode to pass firewall
- ftpClient.enterLocalPassiveMode();
- ftpClient.login(user, pass);
- System.out.println("Connected");
- String remoteDirPath = "D:/WebServer";
- String localDirPath = "D:/Учёба/Сети Тяпаев/Лабы";
- FTPUtil.uploadDirectory(ftpClient, remoteDirPath, localDirPath, "");
- // log out and disconnect from the server
- ftpClient.logout();
- ftpClient.disconnect();
- System.out.println("Disconnected");
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement