gpt4 book ai didi

java - 通过随机访问文件保存日期变量

转载 作者:太空宇宙 更新时间:2023-11-04 13:52:56 25 4
gpt4 key购买 nike

如何在 Java 中使用 RandomAccesFile 编写日期变量?我知道日期变量是 7 个字节,但我不知道如何编写它。

最佳答案

以下是如何使用日期和文件的一些示例。

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);
}

}

关于java - 通过随机访问文件保存日期变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30124656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com