如何在Java中使用RandomAccesFile
编写日期变量?我知道日期变量是7个字节,但我不知道如何写它。
答案 0 :(得分:0)
以下是如何使用Date
和文件的一些示例。
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);
}
}