-1

I am trying to parse multiple file names(doc file)in java. How should I go about doing this?

I asked a previous post and got a answer on how to parse a file name in java. Thanks for that.

So in a directory, I have multiple files(with different names). For instance, there are files

AA_2322_1

AA_2342_1

BB_2324_1

CC_2342_1

I want to parse the middle 4 digit-5digit numbers only.

Laxman Rana
  • 2,904
  • 3
  • 25
  • 37
user17651
  • 45
  • 9

3 Answers3

1

Suppose you have a directory C:\XYZ with the files you listed above, with .doc extensions on them. Taking advantage of a FileFilter, you can get a list of the numbers you are looking for with the following code:

File directory = new File("C:/XYZ");

final ArrayList<String> innerDigits = new ArrayList<String>();

FileFilter filter = new FileFilter() {
    @Override
    public boolean accept(File pathname) {
        if (!pathname.isFile() || !pathname.getName().endsWith("doc"))
            return false;

        // Extract whatever you need from the file object
        String[] parts = pathname.getName().split("_");
        innerDigits.add(parts[1]);

        return true;
    }
};

// No need to store the results, we extracted the info in the filter method
directory.listFiles(filter);

for (String data : innerDigits)
    System.out.println(data);
K Boden
  • 626
  • 4
  • 6
0

Getting the filenames of all files in a folder - Use this question to get the name of all the files in the directory. Then use the String.split() function to parse the file names.

Community
  • 1
  • 1
ageoff
  • 2,798
  • 2
  • 24
  • 39
0

You can use split method

String[] parts = filename.split("_");

Now you need parts[1]

Misa Lazovic
  • 2,805
  • 10
  • 32
  • 38