1

How can I write a date variable using RandomAccesFile in Java? I know a date variable is 7 bytes, but I don't know how to write it.

bytecode77
  • 13,209
  • 30
  • 105
  • 134
sebastia
  • 43
  • 1
  • 4

1 Answers1

0

Here is some example how to work with Date and files.

import java.util.*;
import java.text.*;
import java.io.*;
import java.nio.*;

public class DateExample {

     public static void main(String []args) throws IOException, ParseException {
        /* convert string to Date */
        String time = "May 08 2015 05:19:34";
        DateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss");
        Date outDate = df.parse(time);

        /* write to file */
        System.out.println(outDate + " in one number is " + outDate.getTime());
        RandomAccessFile outFile = new RandomAccessFile("date-file", "rw");
        outFile.write(ByteBuffer.allocate(8).putLong(outDate.getTime()).array());
        outFile.close();

        /* read from file */
        Date inDate = new Date(); 
        RandomAccessFile inFile = new RandomAccessFile("date-file", "r");
        long t = inFile.readLong();
        inDate.setTime(t);
        outFile.close();
        System.out.println("number " + t + " is "+ inDate);
     }

}
Nikolay K
  • 3,670
  • 3
  • 28
  • 37