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
  • 14,163
  • 30
  • 110
  • 141
sebastia
  • 53
  • 1
  • 4
  • "I know Date var is 7 bytes" - in what way? Fundamentally, a `Date` just wraps a `long`, which is 8 bytes... – Jon Skeet May 08 '15 at 13:08
  • Sorry, I am wrong. But I have the same problem, how can I write it? – sebastia May 08 '15 at 13:29
  • It sounds like you have two tasks: 1) Convert the `Date` to a `byte[]`. 2) Write the `byte[]` to a `RandomAccessFile`. Now, do you know how to do *either* of those? – Jon Skeet May 08 '15 at 13:30

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,770
  • 3
  • 25
  • 37