hi4ppl
hi4ppl

Reputation: 625

How to pick certain position from a file name in java

I have bellow class, the files in folder are like (xyz_1_071_basefiles_03272_30087.txt.)

and the position that I have bold I want to pick it that part only and sort it, and from that if the value is not addition like bellow example

it's okay to be like this

10000
10001
10002
10003
10004

but if it's like bellow

10000
10001
10003
10004

then I want to show those two file digits 10001, 10003 as between these two 10002 is missing , bellow is the code I have done so far.

public loopMe() {

         File dir = new File(path);
         File[] directoryListing = dir.listFiles();
         if (directoryListing != null) {
            for (File child : directoryListing) {
                //System.out.println(child.getName());
                String filename = child.getName();
                String filename1 = filename.substring(24,30);
                System.out.println(filename1);
            }
          } else {

          }

    }

Upvotes: 0

Views: 183

Answers (1)

tddmonkey
tddmonkey

Reputation: 21184

Update to include way to get digits from filename:

Integer sequenceNo = Integer.parseInt(filename.split("_")[4]);

This will split the filename on the _ character, then you retrieve the 4th element.

Building on your existing code, convert the part of the filename you've extracted into an Integer (as shown above), put them all into a List and sort it, a bit like this:

List<Integer> filenames = new ArrayList<>();
for (File child : directoryListing) {
    String filename = child.getName();
    String filename1 = filename.substring(24,30);
    filenames.add(Integer.parseInt(filename1));
}
Collections.sort(filenames);

Now loop over the list looking to see if the current entry - 1 > 1 difference, something like this (untested):

int previousInSequence = filenames.get(0);
for (Integer currentSequence : filenames) {
    if (currentSequence - previousInSequence > 1) {
        // you have missing files
        // currentSequence - previousInSequence will tell you how many

    }
}

Upvotes: 1

Related Questions