1

I have a scenario where around 5600 files are present. I am able to retrieve the file names by using the below code:

 String path = "D:\\Projects worked upon\\ANZ\\Anz new\\Files\\329703588_20160328124733595\\Output"; String files;

        File folder = new File(path);
        File[] listOfFiles = folder.listFiles(); 

        for (int i = 0; i < listOfFiles.length; i++) 
        {
            if (listOfFiles[i].isFile()) 
         {
         files = listOfFiles[i].getName();
             if (files.toLowerCase().endsWith(".xml"))
             {
                System.out.println(files);

              }

, but i need only the first part For Eg:if the file name in folder is "abc_Transformed.xml" , i require only abc .. How to get it ?

Rhino 0419
  • 29
  • 2

2 Answers2

0

You can use the substring method to find first string.

 if (files.toLowerCase().endsWith(".xml"))
             {
                String result = files.substring(0, files.indexOf("_"));
                System.out.println(result);               
              }

your whole code

 String path = "D:\\Projects worked upon\\ANZ\\Anz new\\Files\\329703588_20160328124733595\\Output"; String files;     
        File folder = new File(path);
        File[] listOfFiles = folder.listFiles();      
        for (int i = 0; i < listOfFiles.length; i++) 
        { 
         if (listOfFiles[i].isFile()) 
          { 
             files = listOfFiles[i].getName();
             if (files.toLowerCase().endsWith(".xml"))
             { 
               String result = files.substring(0, files.indexOf("_"));
               System.out.println(result);      
              } 
Vipin Jain
  • 3,686
  • 16
  • 35
0

The information about the files is basically irrelevant. You are after some basic String manipulation functions.

You could try something using String.split() like:

String[] pieces = files.split("_");
String first = pieces[0];   // should be equal to "abc"

Or something using String.indexOf() and String.substr() like:

int indexOfUnderscore = files.indexOf("_");
String first = files.substr(0, indexOfUnderscore); // should be equal to "abc"

If you're new to Java, it's worth spending the time to review all the String functions.

dave
  • 11,641
  • 5
  • 47
  • 65