0

我正在尝试编写一个简单的程序来读取文本文件,然后只输出yyyy.MM.dd格式的日期,到控制台问题是我在文件中有一些随机字符串 fe ppppp 2012-12-13 2012-13-06 po2012 我只想要要打印的日期

public class Main {
    public static void main(String... args) {
        String fname = System.getProperty("user.home") + "/Test/dates.txt";
        File f = new File(fname);
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            format.setLenient(false);
            Scanner sc = new Scanner(f);

            ArrayList<String> da = new ArrayList<String>();
            while(sc.hasNext()) {
                da.add(sc.next());
            }
            for (int i = 0;i<da.size()-1; i++) {

                ParsePosition pp = new ParsePosition(0);
                Date d = (Date) format.parse(da.get(i), pp);
                if (d == null) {
                    System.err.println("Invalid date in " + da.get(i));
                    continue;}
                System.out.println(d);
            }
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        }
    }
}
4

1 回答 1

0

按着这些次序

  • 创建 2 个数据格式对象,一个用于解析文本文件中的日期,另一个用于格式化解析的日期以以新格式打印
  • 使用 Reader 逐行读取日期
  • 对于每一行(即读取的日期)--解析--重新格式化--将其打印到控制台
于 2013-05-26T14:54:42.357 回答