Java按指定日期过滤读取文件需求实现求助(附现有代码)
Fix for Reading Only Files Dated 04/17/2019
Let's walk through fixing your code to meet the new requirement—only reading files with the date 04/17/2019, while giving clear feedback for non-matching files. First, let's spot the key issues in your original code that were blocking this functionality:
- The
filesort()method returns immediately after the first file: This means it never checks all files in the list, so you'll only ever get the date of the first file. - Incorrect date format pattern: You used
yyyymmddwheremmrepresents minutes, not months. You needyyyyMMddinstead (uppercaseMMis for months). - Missing full file path: When creating a
Fileobject with just the filename, it looks in your current working directory, not the root pathC:you specified. - Redundant method calls: Calling
filesort()multiple times per file in the loop wastes resources and leads to inconsistent results.
Here's the revised code that fixes all these issues and implements your desired logic:
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.zip.GZIPInputStream; public class FileDateFilterReader { // Keeps your original logic to filter files starting with "B" public static String[] find(String rootPath) { File root = new File(rootPath); FilenameFilter beginsWithB = new FilenameFilter() { public boolean accept(File directory, String filename) { return filename.startsWith("B"); } }; String[] files = root.list(beginsWithB); return files != null ? files : new String[]{"nofile"}; } // Helper method to extract and format the date from a file's name private static String getFormattedFileDate(File file) throws ParseException { String fileName = file.getName(); // Pull out the numeric part of the filename (e.g., "20190417" from "BProce.Arr.20190417..ball10.gz") String numericPart = fileName.replaceAll("\\D+", ""); if (numericPart.length() < 8) { return null; // Invalid date format in filename } String dateString = numericPart.substring(0, 8); // Correct date pattern (MM for months, not mm) DateFormat inputFormatter = new SimpleDateFormat("yyyyMMdd"); Date date = inputFormatter.parse(dateString); // Format to your desired mm/dd/yyyy style DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy"); return outputFormatter.format(date); } public static void main(String[] args) { String rootPath = "C:"; String[] filesList = find(rootPath); String targetDate = "04/17/2019"; for (String fileName : filesList) { // Build the full file path using File.separator for cross-platform compatibility File file = new File(rootPath + File.separator + fileName); if (!file.exists()) { System.out.println("File not found: " + fileName); continue; } try { String fileDate = getFormattedFileDate(file); if (targetDate.equals(fileDate)) { // Read the GZIP file with try-with-resources to auto-close streams try (BufferedReader reader = new BufferedReader( new InputStreamReader( new GZIPInputStream( new FileInputStream(file))))) { String content; System.out.println("\nReading content from: " + fileName); while ((content = reader.readLine()) != null) { System.out.println(content); } } catch (Exception e) { System.out.println("Error reading file " + fileName + ": " + e.getMessage()); } } else { System.out.println("Skipping file (date mismatch): " + fileName + " | File date: " + fileDate); } } catch (ParseException e) { System.out.println("Error parsing date from file " + fileName + ": " + e.getMessage()); } } } }
Key Improvements:
- Reusable Date Logic: The
getFormattedFileDate()method handles all date extraction and formatting, making the code cleaner and easier to adjust later. - Correct Date Handling: Fixed the format pattern to avoid mixing up months and minutes, which was a critical bug in the original code.
- Full Path & Cross-Platform Support: Uses
File.separatorinstead of hardcoding//to work on Windows, macOS, or Linux. - Proper Resource Management: Try-with-resources ensures streams are closed automatically, preventing resource leaks.
- Clear Feedback: Tells you exactly which files are being read, skipped, or causing errors, so you can debug easily.
This code will correctly read only the 04/17/2019 files (BProce.Arr.20190417..ball10.gz and BProce.Arr.20190417.ball23.gz) and skip the 20190416 file, with clear status updates for each file.
内容的提问来源于stack exchange,提问作者SAM
相关产品推荐
相关产品推荐

