-2

I'm trying to filter the files by date and to read each file. I have a find() method that read each filename and it returns a files start by "B" in array. The second method filesort(), it will return all the file dates from filename that sent from find() method. In main method I want to read the file by the specific date i'm giving. if all the files has the same date, it reads all the file. However, from the files one of the file has different date it will throw error.

public static String[] find(String rootPath){

   File root = new File(rootPath);
   // Filter files whose name start with "B"
   FilenameFilter beginswithm = new FilenameFilter() {
       public boolean accept(File directory, String filename) {
           return filename.startsWith("B");
       }
   };
   // array to store filtered file names
   String[] files = root.list(beginswithm);
   String[] no = { "nofile" };
   if (files == null) {
       return no;
   }  
   return files;

}

   public String filesort() throws ParseException {
   String path = "C:";
   String [] filesList = find(path);
   for (String file : filesList) {
       File st = new File(file);
       String name=st.getName();
       name= name.replaceAll("\\D+", "");
       String Datename = name.substring(0, 8);
       DateFormat formatter = new SimpleDateFormat("yyyymmdd");
       Date date = (Date)formatter.parse(Datename);
       SimpleDateFormat newFormat = new SimpleDateFormat("mm/dd/yyyy");
       String finalString = newFormat.format(date);
       return finalString;
   }
   return "error";

}

           public static void main(String[] args){
   String path = "C:";
   String [] filesList = find(path);
       for (String file : filesList) {
   if(filesort().equals("04/17/2019"))//to read all files that has 04/17/2018
    {
   reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(path + "//" +file))));
       String content;
       while ((content = reader.readLine()) != null) {
           System.out.println(content);
           }  
   }
       else if (!filesort().equals("04/17/2019")||filesort()==null ) {
           System.out.println("incorect date");
       }

}

this are the files I'm trying to read
 BProce.Arr.20190416.server10.gz
 BProce.Arr.20190417..ball10.gz
 BProce.Arr.20190417.ball23.gz

because the first file is 04/16/2019, it will throw incorrect date. if 3 of them has 04/17/2019, it will read without issue. but for now i want to read only the file that has a date 04/17/2019

SAM
  • 1
  • 1
  • I very much recommend that you don’t use `SimpleDateFormat` and `Date`. The former is notoriously troublesome, the latter poorly designed too and both fortunately long outdated. You should want to use `LocalDate` and `DateTimeFormatter`, both from [jege.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/index.html). – Ole V.V. Apr 21 '19 at 07:39
  • Could you please: (1) Be clearer about your problem? In Java jargon *throw* means throw an exception, but I am in doubt whether this is your problem? Or what you mean by *throw incorrect date*? (2) Indent and format your code in a more readable way? Use the `{}` button above the edit field to make sure code is formatted as code in the question. Thx. Allow me to be honest: Even after 3 answers I still believe I could contribute something helpful, but I don’t want to struggle my way through your code as it currently stands. – Ole V.V. Apr 21 '19 at 07:53

3 Answers3

1

If we look the problem from another point, it seems very simple to achieve what you want. I will give basic logic.

  1. Read files name from directory. here is example how to do it
  2. Store the names in ArrayList
  3. Sort the ArrayList using Collections following link helps you
  4. Now you have sorted file names of directory whenever you need access just access ArrayList element and using it access real file

Happy Coding, Please let me know if you have still problem

Jasurbek
  • 2,946
  • 3
  • 20
  • 37
1

To find file which name is start on 'B' and contains specific date just follow this procedure.

You can find all file using this code with the File class.

public File[] find(String path) {
    File dir = new File(path);
    File[] listOfFiles = null;
    if (dir.isDirectory()) {
         listOfFiles = dir.listFiles();
    }

    return fileList;
}

From this list of file you can get file name then check this file name start with 'B' and check whether it contains specific date. String object has startsWith() method. You don't need to change date string as Date object. Simply you can check filename contains date string or not.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Rishoban
  • 173
  • 1
  • 2
  • 11
1

Never use the terrible Date, DateFormat, or SimpleDateFormat classes. Use only java.time classes.

The Answer by Rishoban looks correct. Add to that this discussion of parsing date.

Ask if each File object represents a file versus a directory by calling File::isFile. Call File::getName to produce a String with the text of the file name. Then use String::startsWith and String::substring to analyze the file name. Pull out the text of a possible date. Validate by attempting to parse the text as a LocalDate. Define a DateTimeFormatter with a formatting pattern to match your expected inputs.

LocalDate targetDate = LocalDate.of( 2019 , Month.APRIL , 17 ) ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu" ) ;
int lengthOfExpectedDateInput = 10 ; // "01/23/2019" is 10 characters long.
String fileName = file.getName() ;
if( file.isFile() && fileName.startsWith( "B" ) ) {
    String possibleDateInput = fileName.substring( 1 , 1 + lengthOfExpectedDateInput ) ;  // Annoying zero-based index counting where 1 means the 2nd position. 
    try {
        LocalDate ld = LocalDate.parse( possibleDateInput , f ) ;  // Parse string as a `LocalDate` object. If input fails to match formatting pattern, a `DateTimeParseException` is thrown.
        if( ld.isEqual( targetDate ) ) {
            // Handle a valid file with expected file name.
            …
        }
    } catch ( DateTimeParseException e ) {
        // Handle unexpected file name.
        …
    }
}

By the way, educate the publisher of these file names about the ISO 8601 standard. A date should be in format YYYY-MM-DD.

Your Question is really a duplicate of many others. Search Stack Overflow before posting.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154