-1

I have completed the logic copy to dest folder and then delete the source folder after successfully copied. here is my code,

File[] directories = new File("E:\\shareFolder")
                .listFiles(file -> file.isDirectory() && file.getName().matches("[0-9]{6}"));

        for (File getDirectory : directories) {
            try {
                    FileUtils.copyDirectory(new File(getDirectory.getAbsolutePath()),new File("F:\\localFolder"));
                    // here i will check both file size are same if same
                    FileUtils.forceDelete(new File(getDirectory.getAbsolutePath());
                    
                } catch (IOException e) {
                    e.printStackTrace();
                }
        
        }

But now the requirement changed to access the source folder remotely(E://shareFolder to \45.xx.88.xx\shareFolder).

How can achieve existing all condition by access remote folder ?

MMMMS
  • 2,179
  • 9
  • 43
  • 83
  • that requires a `ssh ls` and a `scp`, so don't think you'd be able to do it just with fileUtils. Check here http://www.jcraft.com/jsch/examples/ScpTo.java.html – aran Mar 02 '21 at 06:35
  • Is the remote folder accessible in Windows with UNC pathname `dir \\45.xx.88.xx\shareFolder`? – DuncG Mar 02 '21 at 08:08

1 Answers1

2

It's the same as it would be if you were connecting to the host with ssh because that's what has to go on behind the scenes.

  1. connect to the remote server
  2. delete the file

As suggested in the comments, you could use the JSch library maven documentation.

JSch ssh = new JSch();
Session session = ...
// create and configure session as needed, then connect    
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();

ChannelSftp sftp = (ChannelSftp) channel;

String pathToFile = ...

sftp.rm(pathToFile);
 
channel.disconnect();
session.disconnect();

EDIT

To delete only certain files matching a regex, as asked in the comments, you would have to first get the names of files matching that regex and then iterate over them. An example of this is already available on StackOverflow here.

Adapting it to your case

Vector ls = sftp.ls(path);
Pattern pattern = Pattern.compile("[0-9]{6}");
for (Object entry : ls) {
    ChannelSftp.LsEntry e = (ChannelSftp.LsEntry) entry;
    Matcher m = pattern.matcher(e.getFilename());
    if (m.matches()) {
        sftp.rm(e.getFilename());
    }
}
geco17
  • 5,152
  • 3
  • 21
  • 38
  • Ok, but how to delete only file.getName().matches("[0-9]{6}") ? – MMMMS Mar 02 '21 at 07:09
  • I updated the answer with deletion based on filename patterns – geco17 Mar 02 '21 at 07:17
  • how to rm only 10 days old of folders created date. and i need to loop only folders not files(file.isDirectory() && file.getName().matches("[0-9]{6}") – MMMMS Mar 02 '21 at 07:52