Home > Software design >  Rename top 2 latest pdf in a folder in java
Rename top 2 latest pdf in a folder in java

Time:11-18

I need to write a function in java which can achieve some simple functions.

  • Get names of first 2 latest "pdf"s in a folder
  • Rename those pdfs to first and second respectively.

Here's what I've tried:

    File dir = new File("C:\\Users\\sharm\\Downloads\\");
    File[] files = dir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith(".pdf");
        }});
    
    Arrays.sort(files, new Comparator<File>(){
      public int compare(File f1, File f2) {
        return Long.valueOf(f2.lastModified()).compareTo(f1.lastModified());
      } 
    });
                
    String filenames = Arrays.toString(files);
    filenames = filenames.substring(1, filenames.length() - 1);
    String[] arrOfStr = filenames.split( "," , 3);
    File file = new File(arrOfStr[0]);
    File file2 = new File("Outbound.pdf");
    file.renameTo(file2);
    String secondFileName = arrOfStr[1];
    secondFileName.trim();
    StringBuilder sb = new StringBuilder(secondFileName);
    sb.deleteCharAt(0);
    File file3 = new File(sb.toString());
    File file4 = new File("Inbound.pdf");
    file3.renameTo(file4);

When I did sysout on the second filename to find out that there was a space at the beginning. therefore I decided to eliminate that space using sb. But all said and done, the first filename is changes successfully but the second change does not occur. whereas they are both working on same principle and using same renameTo method. Is there anything that it can be only used once in the code or something? Can anyone please help? I've been scratching my head for the whole day over this.

CodePudding user response:

Try this.

File dir = new File("C:\\Users\\sharm\\Downloads\\");
File[] files = dir.listFiles((d, name) -> name.endsWith(".pdf"));
Arrays.sort(files, Comparator.comparing((File f) -> f.lastModified()).reversed());
files[0].renameTo(new File(dir, "Outbound.pdf"));
files[1].renameTo(new File(dir, "Inbound.pdf"));

CodePudding user response:

I think there is no need to convert list to string and parse it back to Files. Getting first and second by index with renaming them should work:

// after your filtering / sorting code

File firstFile = files.get(0);
File secondFile = files.get(1);'

firstFile.renameTo(new File("Outbound.pdf"));
secondFile.renameTo(new File("Inbound.pdf"));
  • Related