0

I have several files, thing is that i need to know which one was the last created according to the numbers I give them automatically.

For example if i have: file1, file2, file3 I want to receive the file3. I can't do this with "last modified" because I have other folders and files in the same directory.

Also to this last file I would like to increment his number in 1.

Roman C
  • 49,761
  • 33
  • 66
  • 176
eon
  • 67
  • 5
  • 3
    Your best bet is to start implementing it I suppose. – Peter Jaloveczki Jun 13 '13 at 09:04
  • Do you know in which directory is the file ? If yes do they have the same name, except the number ? – Alexis C. Jun 13 '13 at 09:10
  • @ZouZou I know the directory names only that the last number varies. That's it – eon Jun 13 '13 at 09:11
  • what are you **really** trying to achieve ? – Andrea Ligios Jun 13 '13 at 09:13
  • @Andrea Ligios I'm doing a program that gets several files and save them into a folder, when you run the program again that folder name should increment his number into 1 so the files are stored into the new folder, its need to be done that way. – eon Jun 13 '13 at 09:15
  • If you can't use last modified parameter than you need to make sure that the filename is going to be string# where # is a number. Then you can easily load all the directories from the parent folder, go through all of them (make an if to ensure they are folders) and split their filename (int fileNumber = Integer.valueOf(filename.split("file")[1]) or so...) and look for the max. – Lenymm Jun 13 '13 at 09:27

4 Answers4

2

Put the files in a list and sort it lexically, then take the last one.

Ofcourse you have to filter out the ones you are looking for with regex or contains/startswith/endswith

Viktor Mellgren
  • 4,318
  • 3
  • 42
  • 75
  • This won't work with a number greater than 10. It would list Folder1,Folder11,Folder2. Last is 11, but you will get 2... – Andrea Ligios Jun 13 '13 at 09:18
  • @AndreaLigios, true, if the author needs only the number, (s)he can, remove all but the number with replace, and sort it as integers – Viktor Mellgren Jun 13 '13 at 09:20
1

Here is an alternate simple solution.

import java.io.File;

public class FileUtility {

    private static final String FOLDER_PAHT = "D:\\Test";
    private static final String FILE_PREFIX = "file";
    /**
     * @param args
     */
    public static void main(String[] args) {
        int lastFileNumber = getLastFileNumber();
        System.out.println("In folder " + FOLDER_PAHT + " last file is " + FILE_PREFIX + lastFileNumber);
        if(incrementFileNumber(lastFileNumber)) {
            System.out.println("After incrementing the last file becomes : FILE_PREFIX" + lastFileNumber + 1);
        } else {
            System.out.println("Some error occured while updating file number.");
        }

    }

    private static int getLastFileNumber(){
        int maxFileNumber = 0;
        File folder = new File(FOLDER_PAHT);
        File[] listOfFiles = folder.listFiles();
        for (int i = 0; i < listOfFiles.length; i++) {
            String fileName = listOfFiles[i].getName();
            if (listOfFiles[i].isFile() && fileName.contains(FILE_PREFIX)) {
                try {
                    int fileNumber = Integer.parseInt(fileName.substring(FILE_PREFIX.length(), fileName.indexOf(".")));
                    if(maxFileNumber < fileNumber) {
                        maxFileNumber = fileNumber;
                    }
                } catch (NumberFormatException e) {
                    // Because there can be files with starting name as FILE_PREFIX but not valid integer appended to them.
                    //NOthing to do
                }
            } 
        }
        return maxFileNumber;
    }

    private static boolean incrementFileNumber(final int oldNumber) {
        File oldfile =new File(FOLDER_PAHT + File.separator + FILE_PREFIX + oldNumber);
        File newfile =new File(FOLDER_PAHT + File.separator + FILE_PREFIX + (oldNumber + 1) + ".txt");
        return oldfile.renameTo(newfile);
    }
}
Rajendra_Prasad
  • 1,300
  • 4
  • 18
  • 36
Coder
  • 490
  • 4
  • 18
0

Ok, here's an alternative. I'm assuming that the file name is known and they have the same name.

public static void main(String[] args) {
        File dir = new File("directory of the files");
        File [] files = dir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.startsWith("folder");
            }
        });
        for (File file : files) {
            System.out.println(file.getName());
        }
        System.out.println("---------");
        List<File> myFile = new ArrayList<>(Arrays.asList(files));
        Collections.sort(myFile, new Comparator<File>() {

            @Override
            public int compare(File f1, File f2) {
                // TODO Auto-generated method stub
                int numberF1 = Integer.parseInt(f1.getName().replace("folder",""));
                int numberF2 = Integer.parseInt(f2.getName().replace("folder",""));
                return Integer.compare(numberF1, numberF2);
            }
        });

        for (File file : myFile) {
            System.out.println(file.getName());
        }
    }

Output :

folder10
folder2
folder20
folder250
---------
folder2
folder10
folder20
folder250
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
0
    public static void main (String[] args) throws Exception
    {
         File    foldersContainer  = new File("c:/test");
         String  latestFileName    = "";
         Integer highestFileNumber = 0;

         for (File tmpFile : foldersContainer.listFiles()){
             if (tmpFile.isFolder()) {
                int currentNumber = extractFileNumber(tmpFile.getName());
                if (currentNumber > highestFileNumber){
                   highestFileNumber = currentNumber;
                   latestFileName    = tmpFile.getName();
                }
             }
         }             
         latestFileName.replace(highestFileNumber.toString(),
                                (++highestFileNumber).toString());
         System.out.println("Latest file (incremented): " + latestFileName);
    }


    private static int extractFileNumber(String name){          
        for (int x=name.length()-1; x >= 0; x--) 
            if (!Character.isDigit(name.charAt(x))) 
                return Integer.parseInt(name.substring(x+1));
        return -1;
    }

If the filename before the last number can contain numbers, then you should use lastIndexOf to be sure of finding only the occurrence you really want to increment.

instead of

latestFileName.replace(highestFileNumber.toString(),
                       (++highestFileNumber).toString());

you should use

latestFileName = latestFileName
     .substring(0,latestFileName.lastIndexOf(highestFileNumber.toString()))
     .concat((++highestFileNumber).toString());
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243