【发布时间】:2019-04-19 12:20:59
【问题描述】:
我正在尝试按日期过滤文件并读取每个文件。我有一个读取每个文件名的 find() 方法,它返回一个以数组中“B”开头的文件。第二种方法filesort(),它将返回从find()方法发送的文件名中的所有文件日期。在主要方法中,我想在我给出的特定日期之前读取文件。如果所有文件的日期相同,则读取所有文件。但是,从文件中,其中一个文件具有不同的日期,它会引发错误。
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
因为第一个文件是 04/16/2019,它会抛出错误的日期。如果其中 3 个具有 04/17/2019,它将毫无问题地读取。 但现在我只想读取日期为 04/17/2019 的文件
【问题讨论】:
-
我非常建议你不要使用
SimpleDateFormat和Date。前者是出了名的麻烦,后者设计也很糟糕,幸运的是两者都已经过时了。您应该使用LocalDate和DateTimeFormatter,两者都来自jege.time, the modern Java date and time API。 -
能否请您:(1)更清楚您的问题?在 Java 行话中 throw 意味着抛出异常,但我怀疑这是否是你的问题?或者你的意思是抛出不正确的日期? (2) 以更易读的方式缩进和格式化您的代码?使用编辑字段上方的
{}按钮确保代码被格式化为问题中的代码。谢谢。老实说:即使在 3 个答案之后,我仍然相信我可以贡献一些有用的东西,但我不想像现在这样在你的代码中挣扎。