How can I read and write a Date/Calendar to a txt file. I want to store the map of Date,String key value pair to a text file and be able to restore it back into a map. What I did right now is just looping through all of the map and write Date.tostring() + “," + string to the txt file but I don't know how to restore Date.tostring() to a Date, by the way, is there any possibility I only want year/month/date/hour/minutes but no time zone in my Date.tostring() and still restore it back into a Date object?
Asked
Active
Viewed 1.2k times
0
-
possible duplicate of [Serializing Date in Java](http://stackoverflow.com/questions/114575/serializing-date-in-java) – Basil Bourque Jan 20 '15 at 03:23
-
Please search StackOverflow.com before posting. This topic is addressed on hundreds of existing Questions and Answers. – Basil Bourque Jan 20 '15 at 04:03
4 Answers
2
You can save the time to txt file with the format you see in time
variable below and then parse it using the rest of the code.
String time = "Jul 24 2012 05:19:34";
DateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss");
Date date = df.parse(time);

Ali Hashemi
- 3,158
- 3
- 34
- 48
1
You can use this method which creates a folder with a random name and then insert a date to a txt file there:
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();
}

Eyal Sooliman
- 1,876
- 23
- 29
0
you can use SimpleDateFormat for formating date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/HH/mm");
String line = sdf.format(date) + "," + text;
restore
String[] l = line.split(",");
Date d = sdf.parse(l[0]);
String text = l[1];

karci10
- 375
- 3
- 15
0
If you don't want to deal with parsing complex human-readable date strings, the Date.getTime()
function
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMTrepresented by this Date object.
In other words you can get this long
value and write that to file (as a string) instead of a human-readable date string. Then read the long
(as a string) back in from the text file and instantiate with
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

MasterHD
- 2,264
- 1
- 32
- 41