[英]Read and Write Date/Calendar to a txt file in java
如何將日期/日歷讀取和寫入 txt 文件。 我想將 Date,String 鍵值對的映射存儲到文本文件中,並能夠將其恢復回映射。 我現在所做的只是遍歷所有地圖並將 Date.tostring() + “,” + string 寫入 txt 文件,但我不知道如何將 Date.tostring() 恢復為 Date,通過方式,有沒有可能我只想要年/月/日/小時/分鍾,但我的 Date.tostring() 中沒有時區,並且仍然將它恢復回 Date 對象?
您可以使用您在下面的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 以來由此 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.