将日期/日历读写到java中的txt文件中



如何将日期/日历读写到txt文件中。我想将Date,String键值对的映射存储到一个文本文件中,并能够恢复它回到地图上。我现在所做的只是循环浏览所有的映射,并将Date.tostring()+","+字符串写入txt文件,但我不知道如何将Date.tosstring(

您可以使用下面time变量中的格式将时间保存到txt文件中,然后使用其余代码对其进行解析。

String time = "Jul 24 2012 05:19:34";
DateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss");
Date date = df.parse(time);

您可以使用此方法创建一个具有随机名称的文件夹,然后在其中的txt文件中插入日期:

 try {
        Random rand = new Random();
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        Date today = Calendar.getInstance().getTime();
        String reportDate = df.format(today);
        String dateToPrintToFile = reportDate;
        File folder = new File("<your Folder>/" + rand);
        File file = new File("<your Folder>/" + rand + "/testDate.txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(dateToPrintToFile);
        bw.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

您可以使用SimpleDateFormat来格式化日期

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/HH/mm");
String line = sdf.format(date) + "," + text;

恢复

String[] l = line.split(",");
Date d = sdf.parse(l[0]);
String text = l[1];

如果您不想解析复杂的人类可读日期字符串,Date.getTime()函数

返回自1970年1月1日00:00:00 GMT以来由此Date对象表示的毫秒数。

换句话说,您可以获得这个long值,并将其写入文件(作为字符串),而不是人类可读的日期字符串。然后从文本文件中读取回long(作为字符串),并使用进行实例化

String[] l = line.split(","); //Split the line by commas
long value = Long.ParseLong(l[0]); //Parse the string before the comma to a long
Date readDate = new Date(value); //Instantiate a Date using the long

最新更新